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.

Delegate static graph scheduling to execution engine

JPPhoto846031034762
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index d4d7a6fe45..2bcdcb325c 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -89,9 +89,11 @@ effects. Legacy `For`/`ForReturn` continuation scheduling is mirrored by a typed
explicit empty close. `Collect` consumes that buffer when available and retains the materializer/indegree path as its
compatibility adapter. `loop_linkage` remains association metadata and never becomes a data token.
-The engine still owns runtime node materialization and queue readiness for existing snapshots. This is intentional:
-the generic records preserve the tested loop semantics first, while the old execution graph remains the fallback for
-legacy snapshots and unsupported mixed loop shapes. No activation or stream ports are added to author-time graph JSON.
+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:
+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 code under `invokeai/frontend/...`; the existing frontend/backend external interface
remains frozen.
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 45dcc803c2..f4d7049c16 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -7,8 +7,10 @@ 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 expands
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. The runtime also exposes an additive execution-engine seam: frame-scoped gates,
-ordered streams, continuations, and authorized child-dependency records are stored in
+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.
+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
those records become authoritative one behavior at a time.
@@ -46,6 +48,9 @@ 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, 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.
@@ -117,7 +122,9 @@ 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.
+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.
The source graph is treated as stable during normal execution, but the runtime object still exposes guarded graph
mutation helpers. Those helpers reject changes once the affected nodes have already been prepared or executed.
@@ -150,8 +157,9 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre
source node and execution frame.
- `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 attrs): `_ready_queues: dict[class_name, deque[str]]`,
- `_active_class: Optional[str]`. Optional `ready_order: list[str]` to prioritize classes. Queues are rebuilt from
+- **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.
### 4.2 Core methods
@@ -180,8 +188,9 @@ suppresses effects: effect-enabled invocations bypass the ordinary output cache
`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; readiness still comes from materialized execution-graph indegrees and the type-specific control
-paths described below. A future migration may make tokens authoritative only after compatibility is proven.
+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.
Workflow-call note:
@@ -226,7 +235,11 @@ Workflow-call note:
ready work. It owns iterator expansion, collector grouping, prepared-parent selection, and creation of execution-graph
edges. When matching prepared parents for a downstream exec node, skipped prepared exec nodes are ignored and cannot
be selected as live inputs.
-- `_ExecutionScheduler` Owns indegree transitions, class-grouped ready queues, and downstream release on completion.
+- `_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.
+- `_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
@@ -267,18 +280,18 @@ are treated as version 0, while unreadable snapshots are quarantined by the queu
- Deep-copy the source node; assign a fresh ID (and `index` for iterators).
- Cache the preserved iteration path when the materializer has one, such as for grouped collectors.
- Wire edges from chosen prepared parents.
- - Set `indegree = number of unmet inputs` (i.e., parents not yet executed).
+ - Set `indegree = number of unmet inputs` (i.e., parents not yet executed). The generic scheduler mirrors this into
+ its opaque plan for ordinary static DAGs.
- Try to resolve any `If`-specific scheduling state.
- If the node is ready and not deferred by an unresolved `If`, enqueue it into its class queue.
### 4.5 Readiness and class ordering
-- `_enqueue_if_ready(nid)` enqueues by class name only when `indegree == 0`, the node has not already executed, and the
- node is not deferred by an unresolved `If`.
-- `_get_next_node()` returns one node from the `_active_class` queue; when empty, it selects the next nonempty class queue
- (by `ready_order` if set, else alphabetical). Within each class queue, ready exec nodes are ordered by iteration path
- so expanded iterator work runs in a stable outer-to-inner order. No batch-size or fairness cap is currently
- implemented.
+- `_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.
+- `_get_next_node()` uses the generic scheduler for ordinary static DAGs and projects its deterministic class/frame
+ order into the compatibility queues. 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)
@@ -288,8 +301,9 @@ are treated as version 0, while unreadable snapshots are quarantined by the queu
finished yet.
- A node is eligible for enqueue when `indegree[node] == 0`, it has not executed, and it is not deferred by an
unresolved `If`.
-- When a node completes, the scheduler decrements `indegree[child]` for each outgoing edge. Any child that reaches 0 is
- enqueued.
+- When a node completes, the active scheduler decrements `indegree[child]` for each outgoing edge. Any child that
+ reaches 0 is enqueued. The generic plan preserves repeated edges as repeated prerequisites, matching execution-graph
+ indegree semantics.
Example: edges `A->C`, `B->C`, `C->D`. Start: `A:0, B:0, C:2, D:1`. Run `A` -> `C:1`. Run `B` -> `C:0` -> enqueue `C`.
Run `C` -> `D:0` -> enqueue `D`. Run `D` -> done.
diff --git a/invokeai/app/services/shared/execution_engine/__init__.py b/invokeai/app/services/shared/execution_engine/__init__.py
index 39b11e0fe5..6d4619a81a 100644
--- a/invokeai/app/services/shared/execution_engine/__init__.py
+++ b/invokeai/app/services/shared/execution_engine/__init__.py
@@ -26,6 +26,7 @@ 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
__all__ = [
"ChildCompletion",
@@ -50,4 +51,7 @@ __all__ = [
"StreamEnd",
"StreamEvent",
"ExecutionEngineRuntime",
+ "ExecutionPlan",
+ "ExecutionScheduler",
+ "PlanNode",
]
diff --git a/invokeai/app/services/shared/execution_engine/scheduler.py b/invokeai/app/services/shared/execution_engine/scheduler.py
index db4f02e7f3..3084cf8a02 100644
--- a/invokeai/app/services/shared/execution_engine/scheduler.py
+++ b/invokeai/app/services/shared/execution_engine/scheduler.py
@@ -7,13 +7,19 @@ frame values. Graph and invocation semantics belong to adapters above it.
from __future__ import annotations
from dataclasses import dataclass
-from typing import Iterable
-
+from heapq import heapify, heappop, heappush
+from typing import Any, Iterable, Mapping
NodeId = str
Frame = tuple[object, ...]
+def _frame_key(frame: Frame) -> tuple[tuple[str, str], ...]:
+ """Return a stable ordering key for mixed integer/string frame parts."""
+
+ return tuple((type(part).__name__, repr(part)) for part in frame)
+
+
@dataclass(frozen=True, slots=True)
class PlanNode:
"""An opaque executable node and its direct prerequisites."""
@@ -42,11 +48,15 @@ class ExecutionPlan:
) -> PlanNode:
"""Add one node, rejecting duplicate IDs and unknown prerequisites."""
+ if not node_id.strip():
+ raise ValueError("node id must not be blank")
+ if not class_name.strip():
+ raise ValueError("class name must not be blank")
if node_id in self.nodes:
raise ValueError(f"node already exists: {node_id}")
+ # Repeated dependencies represent repeated execution-graph edges and
+ # must remain distinct for indegree accounting.
dependency_ids = tuple(dependencies)
- if len(set(dependency_ids)) != len(dependency_ids):
- raise ValueError(f"duplicate dependencies for node: {node_id}")
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]}")
@@ -65,16 +75,78 @@ class ExecutionPlan:
raise KeyError(f"unknown node: {node_id}")
return tuple(self._dependents[node_id])
+ def snapshot(self) -> dict[str, Any]:
+ """Return a JSON-safe durable projection of this internal plan."""
+
+ return {
+ "nodes": {
+ node_id: {
+ "node_id": node.node_id,
+ "class_name": node.class_name,
+ "frame": list(node.frame),
+ "dependencies": list(node.dependencies),
+ "order": node.order,
+ }
+ for node_id, node in self.nodes.items()
+ },
+ "next_order": self._next_order,
+ }
+
+ @classmethod
+ def from_snapshot(cls, snapshot: Mapping[str, Any]) -> "ExecutionPlan":
+ """Restore a plan using its insertion order and dependency list."""
+
+ plan = cls()
+ raw_nodes = snapshot.get("nodes")
+ if not isinstance(raw_nodes, Mapping):
+ raise ValueError("execution plan snapshot must contain nodes")
+ entries: list[tuple[int, Mapping[str, Any]]] = []
+ for node_key, raw in raw_nodes.items():
+ if not isinstance(raw, Mapping):
+ raise ValueError("execution plan node must be a mapping")
+ if raw.get("node_id") != node_key:
+ raise ValueError("execution plan node key does not match node id")
+ if not isinstance(raw.get("node_id"), str) or not isinstance(raw.get("class_name"), str):
+ raise ValueError("execution plan node id and class name must be strings")
+ order = raw.get("order")
+ if not isinstance(order, int) or order < 0:
+ 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")
+ if not all(isinstance(dependency, str) for dependency in dependencies):
+ raise ValueError("execution plan dependencies must be node ids")
+ entries.append((order, raw))
+ 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", ())),
+ )
+ next_order = snapshot.get("next_order", plan._next_order)
+ if not isinstance(next_order, int) or next_order < plan._next_order:
+ raise ValueError("execution plan next order is invalid")
+ plan._next_order = next_order
+ return plan
+
class ExecutionScheduler:
"""Deterministic scheduler for an :class:`ExecutionPlan`."""
- def __init__(self, plan: ExecutionPlan, ready_order: Iterable[str] = ()) -> None:
+ def __init__(
+ self,
+ plan: ExecutionPlan,
+ ready_order: Iterable[str] = (),
+ executed: Iterable[NodeId] = (),
+ ) -> None:
self.plan = plan
self.ready_order = tuple(ready_order)
- self.executed: set[NodeId] = set()
+ self.executed: set[NodeId] = set(executed)
+ self._claimed: set[NodeId] = set()
self.indegree: dict[NodeId, int] = {}
- self._ready: list[NodeId] = []
+ self._ready: list[tuple[tuple[Any, ...], NodeId]] = []
self._enqueued: set[NodeId] = set()
self.rebuild_ready()
@@ -84,9 +156,13 @@ class ExecutionScheduler:
except ValueError:
return len(self.ready_order)
- def _sort_key(self, node_id: NodeId) -> tuple[int, Frame, int]:
+ def _sort_key(self, node_id: NodeId) -> tuple[Any, ...]:
node = self.plan.nodes[node_id]
- return (self._priority(node.class_name), node.frame, node.order)
+ if self.ready_order:
+ class_key = (self._priority(node.class_name), "")
+ else:
+ class_key = (0, node.class_name)
+ return (*class_key, _frame_key(node.frame), node.order)
def enqueue(self, node_id: NodeId) -> None:
"""Queue a currently-ready node; repeated enqueue is harmless."""
@@ -96,40 +172,88 @@ class ExecutionScheduler:
raise KeyError(f"unknown node: {node_id}")
if node_id in self.executed:
raise ValueError(f"node already completed: {node_id}")
- if self.indegree.get(node_id, 0) != 0:
+ if node_id in self._claimed:
+ return
+ if node_id not in self.indegree:
+ raise KeyError(f"indegree missing for node: {node_id}")
+ if self.indegree[node_id] != 0:
raise ValueError(f"node is not ready: {node_id}")
if node_id not in self._enqueued:
- self._ready.append(node_id)
+ heappush(self._ready, (self._sort_key(node_id), node_id))
self._enqueued.add(node_id)
- self._ready.sort(key=self._sort_key)
def pop_next(self) -> NodeId | None:
"""Remove and return the next ready node ID, or ``None`` when empty."""
if not self._ready:
return None
- node_id = self._ready.pop(0)
+ _, node_id = heappop(self._ready)
self._enqueued.remove(node_id)
+ self._claimed.add(node_id)
return node_id
- def complete(self, node_id: NodeId) -> None:
- """Mark a node complete and release dependents that become ready."""
+ @property
+ def ready_ids(self) -> tuple[NodeId, ...]:
+ """Return queued IDs in the order they will be popped."""
+
+ return tuple(node_id for _, node_id in sorted(self._ready))
+
+ def add_node(self, node: PlanNode) -> None:
+ """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.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:
+ self.enqueue(node.node_id)
+
+ def discard(self, node_id: NodeId) -> None:
+ """Remove a node from queued or claimed work without completing it."""
+
+ self._enqueued.discard(node_id)
+ self._claimed.discard(node_id)
+ self._ready = [(key, queued) for key, queued in self._ready if queued != node_id]
+ heapify(self._ready)
+
+ def set_ready_order(self, ready_order: Iterable[str]) -> None:
+ """Change class priorities while retaining queued and claimed work."""
+
+ self.ready_order = tuple(ready_order)
+ self._ready = [(self._sort_key(node_id), node_id) for node_id in self._enqueued]
+ heapify(self._ready)
+
+ def complete(self, node_id: NodeId) -> tuple[NodeId, ...]:
+ """Mark node complete; return dependents newly made ready."""
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 self.indegree.get(node_id, 0) != 0:
+ if node_id not in self.indegree:
+ raise KeyError(f"indegree missing for node: {node_id}")
+ if self.indegree[node_id] != 0:
raise ValueError(f"node is not ready: {node_id}")
- self.executed.add(node_id)
- self._enqueued.discard(node_id)
- self._ready = [queued for queued in self._ready if queued != node_id]
- for dependent in self.plan.dependents(node_id):
+ dependents = self.plan.dependents(node_id)
+ for dependent in dependents:
+ if dependent not in self.indegree:
+ raise KeyError(f"indegree missing for node: {dependent}")
if self.indegree[dependent] <= 0:
raise ValueError(f"dependency underflow for node: {dependent}")
+ self.executed.add(node_id)
+ self._enqueued.discard(node_id)
+ self._claimed.discard(node_id)
+ self._ready = [(key, queued) for key, queued in self._ready if queued != node_id]
+ # ``complete()`` may be called for a node that was queued but not popped
+ # (for example when a persisted queue is cancelled). Re-establish the
+ # heap invariant after removing it.
+ heapify(self._ready)
+ newly_ready: list[NodeId] = []
+ for dependent in dependents:
self.indegree[dependent] -= 1
if self.indegree[dependent] == 0 and dependent not in self.executed:
self.enqueue(dependent)
+ newly_ready.append(dependent)
+ return tuple(newly_ready)
def rebuild_ready(self) -> None:
"""Recompute indegrees and ready queue from plan and executed IDs."""
@@ -143,11 +267,11 @@ class ExecutionScheduler:
}
self._ready = []
self._enqueued = set()
+ self._claimed = set()
for node_id in self.plan.nodes:
if node_id not in self.executed and self.indegree[node_id] == 0:
- self._ready.append(node_id)
+ heappush(self._ready, (self._sort_key(node_id), node_id))
self._enqueued.add(node_id)
- self._ready.sort(key=self._sort_key)
__all__ = ["ExecutionPlan", "ExecutionScheduler", "PlanNode"]
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 01e75c1310..f86f5985e8 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -75,6 +75,7 @@ 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.invocation_context import InvocationContext
from invokeai.app.util.misc import uuid_string
@@ -1241,6 +1242,9 @@ class _ExecutionMaterializer:
inputs = input_edges if input_edges is not None else self._state.execution_graph._get_input_edges(exec_node_id)
unmet = sum(1 for edge in inputs if edge.source.node_id not in self._state.executed)
self._state._tx_set_mapping(self._state.indegree, exec_node_id, unmet)
+ scheduler = self._state._scheduler()
+ if isinstance(scheduler, _GenericGraphSchedulerAdapter):
+ scheduler.register_node(exec_node_id)
self._state._try_resolve_if_node(exec_node_id)
self._state._enqueue_if_ready(exec_node_id)
@@ -2153,6 +2157,152 @@ class _ExecutionScheduler:
return [(finalized_for_node, finalized_for_output)]
+class _GenericGraphSchedulerAdapter:
+ """Projects the generic scheduler into GraphExecutionState's legacy queues."""
+
+ def __init__(self, state: "GraphExecutionState") -> None:
+ self._state = state
+ prepared_ids = set(state.prepared_source_mapping).intersection(state.executed)
+ self._scheduler = ExecutionScheduler(ExecutionPlan(), state.ready_order, executed=prepared_ids)
+ self._register_existing_nodes()
+ self._sync_indegree()
+ self._project_ready_nodes()
+
+ def _register_existing_nodes(self) -> None:
+ execution_graph = self._state._get_execution_graph_flat()
+ for exec_node_id in nx.topological_sort(execution_graph):
+ self.register_node(exec_node_id)
+
+ def register_node(self, exec_node_id: str) -> None:
+ if exec_node_id in self._scheduler.plan.nodes:
+ return
+ node = self._state.execution_graph.nodes.get(exec_node_id)
+ 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))
+ for dependency in dependencies:
+ if dependency not in self._scheduler.plan.nodes:
+ self.register_node(dependency)
+ self._scheduler.add_node(
+ self._scheduler.plan.add_node(
+ exec_node_id,
+ type(node).__name__,
+ self._state._get_iteration_path(exec_node_id),
+ dependencies,
+ )
+ )
+ self._state._tx_set_mapping(self._state.indegree, exec_node_id, self._scheduler.indegree[exec_node_id])
+ self._project_ready_node(exec_node_id)
+
+ def _sync_indegree(self) -> None:
+ for exec_node_id, degree in self._scheduler.indegree.items():
+ self._state._tx_set_mapping(self._state.indegree, exec_node_id, degree)
+
+ def _project_ready_node(self, exec_node_id: str) -> None:
+ if exec_node_id not in self._scheduler.ready_ids or exec_node_id in self._state._ready_node_ids:
+ return
+ node = self._state.execution_graph.nodes[exec_node_id]
+ cls_name = self._state._type_key(node)
+ queue = self._state._ready_queues.get(cls_name)
+ if queue is None:
+ queue = deque()
+ self._state._tx_set_mapping(self._state._ready_queues, cls_name, queue)
+ iteration_path = self._state._get_iteration_path(exec_node_id)
+ insert_at = next(
+ (
+ index
+ for index, queued_id in enumerate(queue)
+ if self._state._get_iteration_path(queued_id) > iteration_path
+ ),
+ len(queue),
+ )
+ if insert_at == len(queue):
+ self._state._tx_queue_append(queue, exec_node_id)
+ else:
+ self._state._tx_queue_insert(queue, insert_at, exec_node_id)
+ self._state._set_prepared_exec_state(exec_node_id, "ready")
+ self._state._tx_add_set(self._state._ready_node_ids, exec_node_id)
+
+ def _project_ready_nodes(self) -> None:
+ for exec_node_id in self._scheduler.ready_ids:
+ self._project_ready_node(exec_node_id)
+
+ def _remove_projected(self, exec_node_id: str) -> None:
+ for queue in self._state._ready_queues.values():
+ try:
+ self._state._tx_queue_remove(queue, exec_node_id)
+ except ValueError:
+ continue
+ self._state._tx_discard_set(self._state._ready_node_ids, exec_node_id)
+
+ def queue_for(self, cls_name: str) -> Deque[str]:
+ queue = self._state._ready_queues.get(cls_name)
+ if queue is None:
+ queue = deque()
+ self._state._tx_set_mapping(self._state._ready_queues, cls_name, queue)
+ return queue
+
+ def remove_from_ready_queues(self, exec_node_id: str) -> None:
+ self._scheduler.discard(exec_node_id)
+ self._remove_projected(exec_node_id)
+
+ def enqueue_if_ready(self, exec_node_id: str) -> None:
+ self.register_node(exec_node_id)
+ if self._state.indegree.get(exec_node_id) != 0 or exec_node_id in self._state.executed:
+ return
+ self._scheduler.enqueue(exec_node_id)
+ self._project_ready_node(exec_node_id)
+
+ def get_next_node(self) -> Optional[BaseInvocation]:
+ exec_node_id = self._scheduler.pop_next()
+ if exec_node_id is None:
+ return None
+ self._remove_projected(exec_node_id)
+ if exec_node_id in self._state.executed:
+ return self.get_next_node()
+ return self._state.execution_graph.nodes[exec_node_id]
+
+ def _record_completed_node(self, exec_node_id: str, output: BaseInvocationOutput) -> None:
+ self._state._set_prepared_exec_state(exec_node_id, "executed")
+ self._state._tx_add_set(self._state.executed, exec_node_id)
+ self._state._tx_set_mapping(self._state.results, exec_node_id, output)
+
+ def _mark_source_node_complete(self, exec_node_id: str) -> None:
+ 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)
+ and source_node_id not in self._state.executed
+ ):
+ self._state._mark_source_executed(source_node_id)
+
+ def complete(
+ self, exec_node_id: str, output: BaseInvocationOutput
+ ) -> list[tuple[BaseInvocation, BaseInvocationOutput]]:
+ if exec_node_id not in self._state.execution_graph.nodes:
+ return []
+ if exec_node_id not in self._state.indegree:
+ raise KeyError(f"indegree missing for exec node {exec_node_id}")
+ dependents = self._scheduler.plan.dependents(exec_node_id)
+ for dependent in dependents:
+ if dependent not in self._state.indegree:
+ raise KeyError(f"indegree missing for exec node {dependent}")
+ self._remove_projected(exec_node_id)
+ newly_ready = self._scheduler.complete(exec_node_id)
+ self._record_completed_node(exec_node_id, output)
+ self._mark_source_node_complete(exec_node_id)
+ for dependent in set(dependents):
+ self._state._tx_set_mapping(self._state.indegree, dependent, self._scheduler.indegree[dependent])
+ for ready_node_id in newly_ready:
+ self._project_ready_node(ready_node_id)
+ return []
+
+ def set_ready_order(self, ready_order: Iterable[str]) -> None:
+ self._scheduler.set_ready_order(ready_order)
+ self._project_ready_nodes()
+
+
class _ExecutionRuntime:
"""Provides runtime-only helpers such as iteration-path lookup and input hydration."""
@@ -4159,7 +4309,7 @@ class GraphExecutionState(BaseModel):
_prepared_exec_registry: Optional[_PreparedExecRegistry] = PrivateAttr(default=None)
_if_branch_scheduler: Optional[_IfBranchScheduler] = PrivateAttr(default=None)
_execution_materializer: Optional[_ExecutionMaterializer] = PrivateAttr(default=None)
- _execution_scheduler: Optional[_ExecutionScheduler] = PrivateAttr(default=None)
+ _execution_scheduler: Optional[_ExecutionScheduler | _GenericGraphSchedulerAdapter] = PrivateAttr(default=None)
_execution_runtime: Optional[_ExecutionRuntime] = PrivateAttr(default=None)
_for_parent_iteration_paths_cache: dict[str, set[tuple[int, ...]]] = PrivateAttr(default_factory=dict)
_all_for_contexts_finalized_cache: dict[str, bool] = PrivateAttr(default_factory=dict)
@@ -4174,6 +4324,7 @@ class GraphExecutionState(BaseModel):
_for_source_by_return_id: Optional[dict[str, str]] = PrivateAttr(default=None)
_apply_transaction: Optional[_ApplyTransaction] = PrivateAttr(default=None)
_generic_execution_runtime: Optional[ExecutionEngineRuntime] = PrivateAttr(default=None)
+ _generic_graph_scheduler: Optional[_GenericGraphSchedulerAdapter] = PrivateAttr(default=None)
_generic_child_dependencies: dict[str, ChildDependencyRecord] = PrivateAttr(default_factory=dict)
def _tx_record_once(self, key: tuple[Any, ...], undo: Callable[[], None]) -> None:
@@ -4268,6 +4419,7 @@ class GraphExecutionState(BaseModel):
object.__setattr__(self, "_if_branch_scheduler", None)
object.__setattr__(self, "_execution_materializer", None)
object.__setattr__(self, "_execution_scheduler", None)
+ object.__setattr__(self, "_generic_graph_scheduler", None)
object.__setattr__(self, "_execution_runtime", None)
object.__setattr__(self, "_if_branch_exclusive_sources", {})
object.__setattr__(self, "_source_graph_flat", None)
@@ -4368,9 +4520,21 @@ class GraphExecutionState(BaseModel):
self._execution_materializer = _ExecutionMaterializer(self)
return self._execution_materializer
- def _scheduler(self) -> _ExecutionScheduler:
+ def _can_use_generic_scheduler(self) -> bool:
+ """Use generic readiness only for graphs without control-flow lowering."""
+
+ control_nodes = (IfInvocation, IterateInvocation, CollectInvocation, ForInvocation, ForReturnInvocation)
+ return not any(isinstance(node, control_nodes) for node in self.graph.nodes.values()) and not any(
+ isinstance(node, CallSavedWorkflowInvocation) for node in self.graph.nodes.values()
+ )
+
+ def _scheduler(self) -> _ExecutionScheduler | _GenericGraphSchedulerAdapter:
if self._execution_scheduler is None:
- self._execution_scheduler = _ExecutionScheduler(self)
+ if self._can_use_generic_scheduler():
+ self._generic_graph_scheduler = _GenericGraphSchedulerAdapter(self)
+ self._execution_scheduler = self._generic_graph_scheduler
+ else:
+ self._execution_scheduler = _ExecutionScheduler(self)
return self._execution_scheduler
def _runtime(self) -> _ExecutionRuntime:
@@ -5278,6 +5442,8 @@ class GraphExecutionState(BaseModel):
for x in order:
names.append(x.__name__ if hasattr(x, "__name__") else str(x))
self.ready_order = names
+ if self._generic_graph_scheduler is not None:
+ self._generic_graph_scheduler.set_ready_order(names)
def _enqueue_if_ready(self, nid: str) -> None:
self._scheduler().enqueue_if_ready(nid)
@@ -5305,6 +5471,7 @@ class GraphExecutionState(BaseModel):
self._if_branch_scheduler = None
self._execution_materializer = None
self._execution_scheduler = None
+ self._generic_graph_scheduler = None
self._execution_runtime = None
self._source_graph_flat = None
self._execution_graph_flat = None
diff --git a/tests/app/services/shared/test_execution_engine_scheduler.py b/tests/app/services/shared/test_execution_engine_scheduler.py
new file mode 100644
index 0000000000..28791f8d65
--- /dev/null
+++ b/tests/app/services/shared/test_execution_engine_scheduler.py
@@ -0,0 +1,159 @@
+from __future__ import annotations
+
+from unittest.mock import Mock
+
+import pytest
+
+from invokeai.app.invocations.math import AddInvocation, MultiplyInvocation
+from invokeai.app.services.shared.execution_engine.scheduler import (
+ ExecutionPlan,
+ ExecutionScheduler,
+)
+from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph, GraphExecutionState
+
+
+def _plan() -> ExecutionPlan:
+ plan = ExecutionPlan()
+ plan.add_node("left", "AddInvocation")
+ plan.add_node("right", "AddInvocation")
+ plan.add_node("join", "MultiplyInvocation", dependencies=("left", "right"))
+ return plan
+
+
+def test_generic_scheduler_routes_fanout_and_fanin_without_invocation_types() -> None:
+ plan = _plan()
+ scheduler = ExecutionScheduler(plan)
+
+ scheduler.enqueue("left")
+ scheduler.enqueue("right")
+ assert scheduler.pop_next() == "left"
+ assert scheduler.pop_next() == "right"
+ assert scheduler.pop_next() is None
+
+ assert scheduler.complete("left") == ()
+ assert scheduler.complete("right") == ("join",)
+ assert scheduler.pop_next() == "join"
+ assert scheduler.complete("join") == ()
+
+
+def test_generic_scheduler_preserves_ready_class_and_frame_order() -> None:
+ plan = ExecutionPlan()
+ plan.add_node("late", "ZNode", frame=(1,))
+ plan.add_node("early", "ZNode", frame=(0,))
+ plan.add_node("other", "ANode")
+ scheduler = ExecutionScheduler(plan, ready_order=("ZNode", "ANode"))
+
+ for node_id in ("late", "early", "other"):
+ scheduler.enqueue(node_id)
+
+ assert [scheduler.pop_next(), scheduler.pop_next(), scheduler.pop_next()] == ["early", "late", "other"]
+
+
+def test_generic_scheduler_rejects_invalid_completion_without_mutation() -> None:
+ plan = _plan()
+ scheduler = ExecutionScheduler(plan)
+ scheduler.enqueue("left")
+
+ with pytest.raises(KeyError, match="missing"):
+ scheduler.complete("missing")
+ assert scheduler.pop_next() == "left"
+
+ scheduler.complete("left")
+ with pytest.raises(ValueError, match="already completed"):
+ scheduler.complete("left")
+ assert scheduler.indegree == {"left": 0, "right": 0, "join": 1}
+
+
+def test_generic_scheduler_rejects_completion_when_durable_indegree_is_missing() -> None:
+ scheduler = ExecutionScheduler(_plan())
+ scheduler.indegree.pop("join")
+
+ with pytest.raises(KeyError, match="indegree missing"):
+ scheduler.complete("left")
+
+ assert scheduler.executed == set()
+
+
+def test_generic_scheduler_rehydrates_repeated_dependencies() -> None:
+ plan = ExecutionPlan()
+ plan.add_node("source", "Source")
+ plan.add_node("join", "Join", dependencies=("source", "source"))
+
+ scheduler = ExecutionScheduler(plan)
+ assert scheduler.indegree["join"] == 2
+ scheduler.complete("source")
+ assert scheduler.indegree["join"] == 0
+
+
+def test_generic_scheduler_rejects_malformed_snapshot() -> None:
+ with pytest.raises(ValueError, match="node order"):
+ ExecutionPlan.from_snapshot({"nodes": {"node": {"node_id": "node", "order": "first"}}})
+
+
+def test_generic_scheduler_rehydrates_from_durable_projection() -> None:
+ plan = _plan()
+ scheduler = ExecutionScheduler(plan)
+ scheduler.enqueue("left")
+ scheduler.complete("left")
+
+ restored = ExecutionScheduler(
+ ExecutionPlan.from_snapshot(plan.snapshot()),
+ executed=scheduler.executed,
+ )
+ restored.rebuild_ready()
+
+ assert restored.pop_next() == "right"
+ assert restored.indegree["join"] == 1
+
+
+def test_graph_state_static_dag_matches_generic_scheduler_trace() -> None:
+ graph = Graph()
+ graph.add_node(AddInvocation(id="left", a=1, b=2))
+ graph.add_node(AddInvocation(id="right", a=3, b=4))
+ graph.add_node(MultiplyInvocation(id="join"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="left", field="value"),
+ destination=EdgeConnection(node_id="join", field="a"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="right", field="value"),
+ destination=EdgeConnection(node_id="join", field="b"),
+ )
+ )
+
+ state = GraphExecutionState(graph=graph)
+ plan = ExecutionPlan()
+ plan.add_node("left", "AddInvocation")
+ plan.add_node("right", "AddInvocation")
+ plan.add_node("join", "MultiplyInvocation", dependencies=("left", "right"))
+ generic = ExecutionScheduler(plan)
+ generic.enqueue("left")
+ generic.enqueue("right")
+
+ legacy_trace: list[str] = []
+ generic_trace: list[str] = []
+ while (node := state.next()) is not None:
+ legacy_trace.append(state.prepared_source_mapping[node.id])
+ state.complete(node.id, node.invoke(Mock()))
+ while (node_id := generic.pop_next()) is not None:
+ generic_trace.append(node_id)
+ generic.complete(node_id)
+
+ assert legacy_trace == generic_trace
+ assert state.is_complete()
+
+
+def test_graph_state_static_dag_delegates_readiness_to_generic_scheduler() -> None:
+ graph = Graph()
+ graph.add_node(AddInvocation(id="add", a=1, b=2))
+ state = GraphExecutionState(graph=graph)
+
+ node = state.next()
+
+ assert node is not None
+ assert type(state._scheduler()).__name__ == "_GenericGraphSchedulerAdapter"
+ state.complete(node.id, node.invoke(Mock()))
+ assert state.is_complete()