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.

Optimize iterator graph materialization (#9355)

Jonathanbb2c5307f0c3
diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.py
index 0546dabebb..f69928aa1f 100644
--- a/invokeai/app/invocations/baseinvocation.py
+++ b/invokeai/app/invocations/baseinvocation.py
@@ -207,6 +207,10 @@ class BaseInvocation(ABC, BaseModel):
"""Invoke with provided context and return outputs."""
pass
+ def get_event_invocation(self) -> "BaseInvocation":
+ """Returns the invocation representation included in execution events."""
+ return self
+
def invoke_internal(self, context: InvocationContext, services: "InvocationServices") -> BaseInvocationOutput:
"""
Internal invoke method, calls `invoke()` after some prep.
diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.py
index 0294933720..d1a9808df0 100644
--- a/invokeai/app/services/events/events_base.py
+++ b/invokeai/app/services/events/events_base.py
@@ -64,7 +64,7 @@ class EventServiceBase:
def emit_invocation_started(self, queue_item: "SessionQueueItem", invocation: "BaseInvocation") -> None:
"""Emitted when an invocation is started"""
- self.dispatch(InvocationStartedEvent.build(queue_item, invocation))
+ self.dispatch(InvocationStartedEvent.build(queue_item, invocation.get_event_invocation()))
def emit_invocation_progress(
self,
@@ -75,13 +75,15 @@ class EventServiceBase:
image: "ProgressImage | None" = None,
) -> None:
"""Emitted at periodically during an invocation"""
- self.dispatch(InvocationProgressEvent.build(queue_item, invocation, message, percentage, image))
+ self.dispatch(
+ InvocationProgressEvent.build(queue_item, invocation.get_event_invocation(), message, percentage, image)
+ )
def emit_invocation_complete(
self, queue_item: "SessionQueueItem", invocation: "BaseInvocation", output: "BaseInvocationOutput"
) -> None:
"""Emitted when an invocation is complete"""
- self.dispatch(InvocationCompleteEvent.build(queue_item, invocation, output))
+ self.dispatch(InvocationCompleteEvent.build(queue_item, invocation.get_event_invocation(), output))
def emit_invocation_error(
self,
@@ -92,7 +94,15 @@ class EventServiceBase:
error_traceback: str,
) -> None:
"""Emitted when an invocation encounters an error"""
- self.dispatch(InvocationErrorEvent.build(queue_item, invocation, error_type, error_message, error_traceback))
+ self.dispatch(
+ InvocationErrorEvent.build(
+ queue_item,
+ invocation.get_event_invocation(),
+ error_type,
+ error_message,
+ error_traceback,
+ )
+ )
# endregion
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index dc5e67a8b3..a18741a9c9 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -33,7 +33,7 @@ from invokeai.app.services.session_processor.workflow_call_runtime import (
WorkflowCallQueueLifecycle,
)
from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem, SessionQueueItemNotFoundError
-from invokeai.app.services.shared.graph import NodeInputError
+from invokeai.app.services.shared.graph import CollectInvocation, IterateInvocation, NodeInputError
from invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_context
from invokeai.app.util.profiler import Profiler
@@ -141,10 +141,19 @@ class DefaultSessionRunner(SessionRunnerBase):
# Invoke the node
output = invocation.invoke_internal(context=context, services=self._services)
+ control_collection = None
+ if self._on_after_run_node_callbacks and isinstance(invocation, (IterateInvocation, CollectInvocation)):
+ control_collection = invocation.collection
# Save output and history
queue_item.session.complete(invocation.id, output)
- self._on_after_run_node(invocation, queue_item, output)
+ if control_collection is not None:
+ invocation.collection = control_collection
+ try:
+ self._on_after_run_node(invocation, queue_item, output)
+ finally:
+ if control_collection is not None:
+ invocation.collection = []
except CanceledException:
# A CanceledException is raised during the denoising step callback if the cancel event is set. We don't need
@@ -215,7 +224,7 @@ class DefaultSessionRunner(SessionRunnerBase):
# The queue item may have been canceled or failed while the session was running. We should only complete it
# if it is not already canceled or failed.
if queue_item.status not in ["canceled", "failed"] and queue_item.session.is_complete():
- queue_item = self._services.session_queue.complete_queue_item(queue_item.item_id)
+ queue_item = self._services.session_queue.complete_queue_item(queue_item.item_id, queue_item=queue_item)
# We'll get a GESStatsNotFoundError if we try to log stats for an untracked graph, but in the processor
# we don't care about that - suppress the error.
diff --git a/invokeai/app/services/session_processor/workflow_call_runtime.py b/invokeai/app/services/session_processor/workflow_call_runtime.py
index 4757647510..e85c07922d 100644
--- a/invokeai/app/services/session_processor/workflow_call_runtime.py
+++ b/invokeai/app/services/session_processor/workflow_call_runtime.py
@@ -96,7 +96,7 @@ class WorkflowCallCoordinator:
child_queue_item = None
enqueued_child_item_ids: list[int] = []
try:
- self._session_runner._services.session_queue.set_queue_item_session(queue_item.item_id, queue_item.session)
+ self._session_runner._services.session_queue.save_queue_item_session(queue_item.item_id, queue_item.session)
for child_result in child_session_results:
child_queue_item = self._session_runner._services.session_queue.enqueue_workflow_call_child(
parent_queue_item=queue_item,
@@ -105,8 +105,8 @@ class WorkflowCallCoordinator:
)
enqueued_child_item_ids.append(child_queue_item.item_id)
queue_item.session.set_waiting_workflow_call_child_item_ids(enqueued_child_item_ids)
- self._session_runner._services.session_queue.set_queue_item_session(queue_item.item_id, queue_item.session)
- self._session_runner._services.session_queue.suspend_queue_item(queue_item.item_id)
+ self._session_runner._services.session_queue.save_queue_item_session(queue_item.item_id, queue_item.session)
+ self._session_runner._services.session_queue.suspend_queue_item(queue_item.item_id, queue_item=queue_item)
except Exception as e:
if enqueued_child_item_ids:
self._session_runner._services.session_queue.delete_queue_items_by_id(enqueued_child_item_ids)
@@ -218,7 +218,7 @@ class WorkflowCallQueueLifecycle:
self._fail_parent_from_failed_child(parent_queue_item)
return
if not should_resume_parent:
- self._session_runner._services.session_queue.set_queue_item_session(
+ self._session_runner._services.session_queue.save_queue_item_session(
parent_queue_item.item_id, parent_queue_item.session
)
return
@@ -228,17 +228,19 @@ class WorkflowCallQueueLifecycle:
parent_output = WorkflowReturnOutput(values=aggregated_values)
parent_queue_item.session.complete(waiting_invocation.id, parent_output)
self._session_runner._on_after_run_node(waiting_invocation, parent_queue_item, parent_output)
- parent_queue_item = self._session_runner._services.session_queue.set_queue_item_session(
+ self._session_runner._services.session_queue.save_queue_item_session(
parent_queue_item.item_id, parent_queue_item.session
)
if parent_queue_item.session.is_complete():
parent_queue_item = self._session_runner._services.session_queue.complete_queue_item(
- parent_queue_item.item_id
+ parent_queue_item.item_id, queue_item=parent_queue_item
)
if getattr(parent_queue_item, "parent_item_id", None) is not None:
self._resume_parent_from_completed_child(parent_queue_item)
return
- self._session_runner._services.session_queue.resume_queue_item(parent_queue_item.item_id)
+ self._session_runner._services.session_queue.resume_queue_item(
+ parent_queue_item.item_id, queue_item=parent_queue_item
+ )
def _fail_parent_from_failed_child(self, child_queue_item: SessionQueueItem) -> None:
parent_queue_item = self._get_parent_queue_item(child_queue_item)
diff --git a/invokeai/app/services/session_queue/session_queue_base.py b/invokeai/app/services/session_queue/session_queue_base.py
index 2737816d71..2cef8c81a8 100644
--- a/invokeai/app/services/session_queue/session_queue_base.py
+++ b/invokeai/app/services/session_queue/session_queue_base.py
@@ -92,8 +92,8 @@ class SessionQueueBase(ABC):
acting_user_id is independent of user_id and controls only current-item redaction:
when set, the returned status omits item_id/session_id/batch_id unless the
currently-running item belongs to acting_user_id. The redaction is decided from the
- same get_current() snapshot used to embed those identifiers, so it cannot race against
- a concurrent state change.
+ same database snapshot used to embed those identifiers, so it cannot race against a
+ concurrent state change.
is_admin disables current-item redaction entirely: admins may see the identifiers of
any user's current item. Redaction stays fail-closed - a caller that passes user_id
@@ -114,17 +114,17 @@ class SessionQueueBase(ABC):
pass
@abstractmethod
- def complete_queue_item(self, item_id: int) -> SessionQueueItem:
+ def complete_queue_item(self, item_id: int, queue_item: Optional[SessionQueueItem] = None) -> SessionQueueItem:
"""Completes a session queue item"""
pass
@abstractmethod
- def suspend_queue_item(self, item_id: int) -> SessionQueueItem:
+ def suspend_queue_item(self, item_id: int, queue_item: Optional[SessionQueueItem] = None) -> SessionQueueItem:
"""Suspends a session queue item while waiting on a child workflow execution."""
pass
@abstractmethod
- def resume_queue_item(self, item_id: int) -> SessionQueueItem:
+ def resume_queue_item(self, item_id: int, queue_item: Optional[SessionQueueItem] = None) -> SessionQueueItem:
"""Resumes a suspended session queue item by returning it to pending state."""
pass
@@ -228,6 +228,11 @@ class SessionQueueBase(ABC):
"""Sets the session for a session queue item. Use this to update the session state."""
pass
+ @abstractmethod
+ def save_queue_item_session(self, item_id: int, session: GraphExecutionState) -> None:
+ """Persists a queue item's session without loading and returning the full queue item."""
+ pass
+
@abstractmethod
def enqueue_workflow_call_child(
self,
diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.py
index e845d663ef..68f4ee27f3 100644
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@ -308,7 +308,9 @@ class SqliteSessionQueue(SessionQueueBase):
if result is None:
return None
queue_item = SessionQueueItem.queue_item_from_dict(dict(result))
- queue_item = self._set_queue_item_status(item_id=queue_item.item_id, status="in_progress")
+ queue_item = self._set_queue_item_status(
+ item_id=queue_item.item_id, status="in_progress", queue_item=queue_item
+ )
return queue_item
def get_next(self, queue_id: str) -> Optional[SessionQueueItem]:
@@ -365,7 +367,12 @@ class SqliteSessionQueue(SessionQueueBase):
error_type: Optional[str] = None,
error_message: Optional[str] = None,
error_traceback: Optional[str] = None,
+ queue_item: Optional[SessionQueueItem] = None,
) -> SessionQueueItem:
+ if queue_item is not None and queue_item.item_id != item_id:
+ raise ValueError(f"Queue item {queue_item.item_id} does not match requested item {item_id}")
+
+ updated_status_row: sqlite3.Row | None = None
with self._db.transaction() as cursor:
cursor.execute(
"""--sql
@@ -374,31 +381,53 @@ class SqliteSessionQueue(SessionQueueBase):
(item_id,),
)
row = cursor.fetchone()
- if row is None:
- raise SessionQueueItemNotFoundError(f"No queue item with id {item_id}")
- current_status = row[0]
+ if row is None:
+ raise SessionQueueItemNotFoundError(f"No queue item with id {item_id}")
+ current_status = row[0]
- # Only update if not already finished (completed, failed or canceled)
- if current_status in ("completed", "failed", "canceled"):
- return self.get_queue_item(item_id)
+ # Only update if not already finished (completed, failed or canceled).
+ if current_status not in ("completed", "failed", "canceled"):
+ cursor.execute(
+ """--sql
+ UPDATE session_queue
+ SET status = ?, status_sequence = COALESCE(status_sequence, 0) + 1, error_type = ?, error_message = ?, error_traceback = ?
+ WHERE item_id = ?
+ """,
+ (status, error_type, error_message, error_traceback, item_id),
+ )
+ cursor.execute(
+ """--sql
+ SELECT
+ status,
+ status_sequence,
+ error_type,
+ error_message,
+ error_traceback,
+ created_at,
+ updated_at,
+ started_at,
+ completed_at
+ FROM session_queue
+ WHERE item_id = ?
+ """,
+ (item_id,),
+ )
+ updated_status_row = cast(sqlite3.Row, cursor.fetchone())
- with self._db.transaction() as cursor:
- cursor.execute(
- """--sql
- UPDATE session_queue
- SET status = ?, status_sequence = COALESCE(status_sequence, 0) + 1, error_type = ?, error_message = ?, error_traceback = ?
- WHERE item_id = ?
- """,
- (status, error_type, error_message, error_traceback, item_id),
- )
+ if updated_status_row is None:
+ return self.get_queue_item(item_id)
- queue_item = self.get_queue_item(item_id)
+ if queue_item is None:
+ queue_item = self.get_queue_item(item_id)
+ else:
+ for field_name in updated_status_row.keys():
+ setattr(queue_item, field_name, updated_status_row[field_name])
batch_status = self.get_batch_status(queue_id=queue_item.queue_id, batch_id=queue_item.batch_id)
# The QueueItemStatusChangedEvent ships to user:{queue_item.user_id} and admin rooms.
# acting_user_id ensures the embedded current-item identifiers are redacted when the
# in-progress item belongs to someone else, while leaving aggregate counts global.
# Doing this inside get_queue_status guarantees the redaction decision and the
- # embedded identifiers come from the same get_current() snapshot — eliminating the
+ # embedded identifiers come from the same lightweight metadata snapshot, eliminating the
# race where a second read could find None and skip scrubbing stale identifiers.
# user_id additionally embeds the owner's per-user counts so the owner's client can
# apply the event's queue_status optimistically without waiting for a refetch; the
@@ -600,16 +629,16 @@ class SqliteSessionQueue(SessionQueueBase):
self.cancel_queue_item(item_id)
self.delete_queue_items_by_id(chain_item_ids)
- def complete_queue_item(self, item_id: int) -> SessionQueueItem:
- queue_item = self._set_queue_item_status(item_id=item_id, status="completed")
+ def complete_queue_item(self, item_id: int, queue_item: Optional[SessionQueueItem] = None) -> SessionQueueItem:
+ queue_item = self._set_queue_item_status(item_id=item_id, status="completed", queue_item=queue_item)
return queue_item
- def suspend_queue_item(self, item_id: int) -> SessionQueueItem:
- queue_item = self._set_queue_item_status(item_id=item_id, status="waiting")
+ def suspend_queue_item(self, item_id: int, queue_item: Optional[SessionQueueItem] = None) -> SessionQueueItem:
+ queue_item = self._set_queue_item_status(item_id=item_id, status="waiting", queue_item=queue_item)
return queue_item
- def resume_queue_item(self, item_id: int) -> SessionQueueItem:
- queue_item = self._set_queue_item_status(item_id=item_id, status="pending")
+ def resume_queue_item(self, item_id: int, queue_item: Optional[SessionQueueItem] = None) -> SessionQueueItem:
+ queue_item = self._set_queue_item_status(item_id=item_id, status="pending", queue_item=queue_item)
return queue_item
def fail_queue_item(
@@ -913,11 +942,10 @@ class SqliteSessionQueue(SessionQueueBase):
raise SessionQueueItemNotFoundError(f"No queue item with id {item_id}")
return SessionQueueItem.queue_item_from_dict(dict(result))
- def set_queue_item_session(self, item_id: int, session: GraphExecutionState) -> SessionQueueItem:
+ def save_queue_item_session(self, item_id: int, session: GraphExecutionState) -> None:
with self._db.transaction() as cursor:
# Use exclude_none so we don't end up with a bunch of nulls in the graph - this can cause validation errors
- # when the graph is loaded. Graph execution occurs purely in memory - the session saved here is not referenced
- # during execution.
+ # when the graph is loaded. Persisted sessions are used to resume execution across queue boundaries.
session_json = session.model_dump_json(warnings=False, exclude_none=True)
cursor.execute(
"""--sql
@@ -927,6 +955,11 @@ class SqliteSessionQueue(SessionQueueBase):
""",
(session_json, item_id),
)
+ if cursor.rowcount == 0:
+ raise SessionQueueItemNotFoundError(f"No queue item with id {item_id}")
+
+ def set_queue_item_session(self, item_id: int, session: GraphExecutionState) -> SessionQueueItem:
+ self.save_queue_item_session(item_id, session)
return self.get_queue_item(item_id)
def enqueue_workflow_call_child(
@@ -1193,7 +1226,17 @@ class SqliteSessionQueue(SessionQueueBase):
)
user_counts_result = cast(list[sqlite3.Row], cursor.fetchall())
- current_item = self.get_current(queue_id=queue_id)
+ cursor.execute(
+ """--sql
+ SELECT item_id, session_id, batch_id, user_id
+ FROM session_queue
+ WHERE queue_id = ? AND status = 'in_progress'
+ LIMIT 1
+ """,
+ (queue_id,),
+ )
+ current_item = cast(Union[sqlite3.Row, None], cursor.fetchone())
+
total = sum(row[1] or 0 for row in counts_result)
counts: dict[str, int] = {row[0]: row[1] for row in counts_result}
@@ -1213,15 +1256,19 @@ class SqliteSessionQueue(SessionQueueBase):
# admin callers can pass their user_id (for the per-user counts) without losing
# visibility of other users' current item.
owner_user_id = user_id if acting_user_id is None else acting_user_id
- show_current_item = current_item is not None and (
- is_admin or owner_user_id is None or current_item.user_id == owner_user_id
- )
+ current_item_id = None
+ current_session_id = None
+ current_batch_id = None
+ if current_item is not None and (is_admin or owner_user_id is None or current_item["user_id"] == owner_user_id):
+ current_item_id = current_item["item_id"]
+ current_session_id = current_item["session_id"]
+ current_batch_id = current_item["batch_id"]
return SessionQueueStatus(
queue_id=queue_id,
- item_id=current_item.item_id if show_current_item else None,
- session_id=current_item.session_id if show_current_item else None,
- batch_id=current_item.batch_id if show_current_item else None,
+ item_id=current_item_id,
+ session_id=current_session_id,
+ batch_id=current_batch_id,
pending=counts.get("pending", 0),
in_progress=counts.get("in_progress", 0),
waiting=counts.get("waiting", 0),
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index d65e5213cc..c6bd7eb340 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -2,9 +2,25 @@
import copy
import itertools
+import weakref
from collections import deque
from dataclasses import dataclass
-from typing import Any, Deque, Iterable, Literal, Optional, Type, TypeVar, Union, get_args, get_origin
+from functools import wraps
+from typing import (
+ Any,
+ Callable,
+ Concatenate,
+ Deque,
+ Iterable,
+ Literal,
+ Optional,
+ ParamSpec,
+ Type,
+ TypeVar,
+ Union,
+ get_args,
+ get_origin,
+)
import networkx as nx
from pydantic import (
@@ -47,6 +63,8 @@ COLLECTION_FIELD = "collection"
class EdgeConnection(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
node_id: str = Field(description="The id of the node for this edge connection")
field: str = Field(description="The field for this connection")
@@ -62,6 +80,8 @@ class EdgeConnection(BaseModel):
class Edge(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
source: EdgeConnection = Field(description="The connection for the edge's from node and field")
destination: EdgeConnection = Field(description="The connection for the edge's to node and field")
@@ -138,14 +158,17 @@ class _PreparedExecRegistry:
self,
prepared_source_mapping: dict[str, str],
source_prepared_mapping: dict[str, set[str]],
+ prepared_iteration_paths: dict[str, tuple[int, ...]],
metadata: dict[str, _PreparedExecNodeMetadata],
) -> None:
self._prepared_source_mapping = prepared_source_mapping
self._source_prepared_mapping = source_prepared_mapping
+ self._prepared_iteration_paths = prepared_iteration_paths
self._metadata = metadata
def register(self, exec_node_id: str, source_node_id: str) -> None:
self._prepared_source_mapping[exec_node_id] = source_node_id
+ self._prepared_iteration_paths.pop(exec_node_id, None)
self._metadata[exec_node_id] = _PreparedExecNodeMetadata(source_node_id=source_node_id)
if source_node_id not in self._source_prepared_mapping:
self._source_prepared_mapping[source_node_id] = set()
@@ -172,9 +195,15 @@ class _PreparedExecRegistry:
def get_iteration_path(self, exec_node_id: str) -> Optional[tuple[int, ...]]:
metadata = self._metadata.get(exec_node_id)
- return metadata.iteration_path if metadata is not None else None
+ if metadata is not None and metadata.iteration_path is not None:
+ return metadata.iteration_path
+ iteration_path = self._prepared_iteration_paths.get(exec_node_id)
+ if iteration_path is not None:
+ self.get_metadata(exec_node_id).iteration_path = iteration_path
+ return iteration_path
def set_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> None:
+ self._prepared_iteration_paths[exec_node_id] = iteration_path
self.get_metadata(exec_node_id).iteration_path = iteration_path
@@ -282,7 +311,6 @@ class _IfBranchScheduler:
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)
- iteration_path = self._state._get_iteration_path(exec_node_id)
for source_if_id, source_if_node in self._state.graph.nodes.items():
if not isinstance(source_if_node, IfInvocation):
@@ -292,6 +320,7 @@ class _IfBranchScheduler:
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
@@ -345,6 +374,52 @@ class _ExecutionMaterializer:
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
+ self._iteration_axes_by_source: dict[str, tuple[str, ...]] = {}
+
+ def _get_iteration_axes(self, source_node_id: str) -> tuple[str, ...]:
+ cached = self._iteration_axes_by_source.get(source_node_id)
+ if cached is not None:
+ return cached
+
+ axes = self._state._runtime()._get_ordered_iterator_sources(source_node_id)
+ if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
+ axes.append(source_node_id)
+ result = tuple(axes)
+ self._iteration_axes_by_source[source_node_id] = result
+ return result
+
+ def _get_known_iteration_path(
+ self,
+ iteration_index: int,
+ iteration_node_map: list[tuple[str, str]],
+ ) -> Optional[tuple[int, ...]]:
+ parent_paths: list[tuple[int, ...]] = []
+ parent_iteration_axes: list[tuple[str, ...]] = []
+ registry = self._state._prepared_registry()
+ for source_node_id, prepared_id in iteration_node_map:
+ parent_path = registry.get_iteration_path(prepared_id)
+ if parent_path is None:
+ return None
+ if parent_path:
+ parent_paths.append(parent_path)
+ parent_iteration_axes.append(self._get_iteration_axes(source_node_id))
+
+ unique_parent_paths = set(parent_paths)
+ paths_share_iteration_axes = len(set(parent_iteration_axes)) <= 1
+
+ # Materialized iteration boundaries use non-negative indexes; ordinary execution nodes use -1. Keeping this
+ # generic allows other scheduler-managed loop nodes to reuse the same path cache.
+ if iteration_index >= 0:
+ if len(unique_parent_paths) > 1 or not paths_share_iteration_axes:
+ return None
+ parent_path = next(iter(unique_parent_paths), ())
+ return (*parent_path, iteration_index)
+
+ if not unique_parent_paths:
+ return ()
+ if len(unique_parent_paths) == 1 and paths_share_iteration_axes:
+ return next(iter(unique_parent_paths))
+ return None
def _get_iterator_iteration_count(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> int:
input_collection_edge = next(iter(self._state.graph._get_input_edges(node_id, COLLECTION_FIELD)))
@@ -391,21 +466,28 @@ class _ExecutionMaterializer:
if isinstance(new_node, IterateInvocation):
new_node.index = iteration_index
+ # Scheduler-managed iteration boundaries and collectors are cheaper to execute than to hash, especially when
+ # their inputs contain large collections. Loop body nodes retain their normal cache behavior.
+ if iteration_index >= 0 or isinstance(new_node, CollectInvocation):
+ new_node.use_cache = False
+
self._state.execution_graph.add_node(new_node)
self._state._register_prepared_exec_node(new_node.id, node_id)
return new_node
- def _attach_execution_edges(self, exec_node_id: str, new_edges: list[Edge]) -> None:
- for edge in new_edges:
- self._state.execution_graph._add_execution_edge(
- Edge(
- source=edge.source,
- destination=EdgeConnection(node_id=exec_node_id, field=edge.destination.field),
- )
+ def _attach_execution_edges(self, exec_node_id: str, new_edges: list[Edge]) -> list[Edge]:
+ attached_edges = [
+ Edge(
+ source=edge.source,
+ destination=EdgeConnection(node_id=exec_node_id, field=edge.destination.field),
)
+ for edge in new_edges
+ ]
+ self._state.execution_graph._extend_edges_unchecked(attached_edges)
+ return attached_edges
- def _initialize_execution_node(self, exec_node_id: str) -> None:
- inputs = self._state.execution_graph._get_input_edges(exec_node_id)
+ def _initialize_execution_node(self, exec_node_id: str, input_edges: Optional[list[Edge]] = None) -> None:
+ 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.indegree[exec_node_id] = unmet
self._state._try_resolve_if_node(exec_node_id)
@@ -551,29 +633,92 @@ class _ExecutionMaterializer:
self._state.executed.add(source_node_id)
self._state.executed_history.append(source_node_id)
- def _get_parent_iteration_mappings(self, next_node_id: str, graph: nx.DiGraph) -> list[list[tuple[str, str]]]:
+ def _index_prepared_nodes_by_iteration_path(self, prepared_nodes: set[str]) -> dict[tuple[int, ...], list[str]]:
+ prepared_nodes_by_iteration_path: dict[tuple[int, ...], list[str]] = {}
+ for prepared_id in prepared_nodes:
+ iteration_path = self._state._get_iteration_path(prepared_id)
+ prepared_nodes_by_iteration_path.setdefault(iteration_path, []).append(prepared_id)
+ return prepared_nodes_by_iteration_path
+
+ def _get_target_iteration_path(
+ self, source_node_id: str, graph: nx.DiGraph, prepared_iterator_nodes: tuple[str, ...]
+ ) -> Optional[tuple[int, ...]]:
+ parent_iterators = self._get_parent_iterator_exec_nodes(source_node_id, graph, list(prepared_iterator_nodes))
+ parent_paths = [self._state._get_iteration_path(prepared_id) for prepared_id, _ in parent_iterators]
+ if not parent_paths:
+ return ()
+
+ target_path = max(parent_paths, key=len)
+ if all(target_path[: len(parent_path)] == parent_path for parent_path in parent_paths):
+ return target_path
+ return None
+
+ def _get_indexed_iteration_node(
+ self,
+ source_node_id: str,
+ graph: nx.DiGraph,
+ prepared_iterator_nodes: tuple[str, ...],
+ prepared_nodes_by_iteration_path: dict[tuple[int, ...], list[str]],
+ ) -> Optional[str]:
+ target_path = self._get_target_iteration_path(source_node_id, graph, prepared_iterator_nodes)
+ if target_path is None:
+ return None
+
+ for path_length in range(len(target_path), -1, -1):
+ candidates = prepared_nodes_by_iteration_path.get(target_path[:path_length], [])
+ if len(candidates) == 1:
+ return candidates[0]
+ if len(candidates) > 1:
+ return None
+ return None
+
+ def _get_parent_iteration_mappings(self, next_node_id: str, graph: nx.DiGraph) -> Iterable[list[tuple[str, str]]]:
parent_node_ids = [source_id for source_id, _ in graph.in_edges(next_node_id)]
iterator_graph = self.iterator_graph(graph)
iterator_nodes = self.get_node_iterators(next_node_id, iterator_graph)
if not iterator_nodes:
- return self._get_parent_iteration_mappings_without_iterators(parent_node_ids)
-
- iterator_nodes_prepared = [list(self._state.source_prepared_mapping[node_id]) for node_id in iterator_nodes]
- iterator_node_prepared_combinations = list(itertools.product(*iterator_nodes_prepared))
+ return iter(self._get_parent_iteration_mappings_without_iterators(parent_node_ids))
- execution_graph = self._state.execution_graph.nx_graph_flat()
- prepared_parent_mappings = [
- [
- (node_id, self.get_iteration_node(node_id, graph, execution_graph, prepared_iterators))
- for node_id in parent_node_ids
- ]
- for prepared_iterators in iterator_node_prepared_combinations
- ]
- return [
- mapping
- for mapping in prepared_parent_mappings
- if all(prepared_id is not None for _, prepared_id in mapping)
+ iterator_nodes_prepared = [
+ sorted(self._state.source_prepared_mapping[node_id], key=self._state._get_iteration_path)
+ for node_id in iterator_nodes
]
+ prepared_nodes_by_source = {
+ node_id: self._get_prepared_nodes_for_source(node_id) for node_id in parent_node_ids
+ }
+ prepared_nodes_by_source_and_path = {
+ node_id: self._index_prepared_nodes_by_iteration_path(prepared_nodes)
+ for node_id, prepared_nodes in prepared_nodes_by_source.items()
+ }
+
+ def iter_mappings() -> Iterable[list[tuple[str, str]]]:
+ execution_graph: Optional[nx.DiGraph] = None
+ for prepared_iterators in itertools.product(*iterator_nodes_prepared):
+ mapping: list[tuple[str, str]] = []
+ for node_id in parent_node_ids:
+ prepared_id = self._get_indexed_iteration_node(
+ node_id,
+ graph,
+ prepared_iterators,
+ prepared_nodes_by_source_and_path[node_id],
+ )
+ if prepared_id is None:
+ if execution_graph is None:
+ execution_graph = self._state.execution_graph.nx_graph_flat()
+ prepared_id = self.get_iteration_node(
+ node_id,
+ graph,
+ execution_graph,
+ list(prepared_iterators),
+ prepared_nodes_by_source[node_id],
+ )
+ if prepared_id is None:
+ break
+ mapping.append((node_id, prepared_id))
+ if len(mapping) == len(parent_node_ids):
+ yield mapping
+
+ return iter(iter_mappings())
def create_execution_node(
self,
@@ -592,13 +737,15 @@ class _ExecutionMaterializer:
new_nodes: list[str] = []
for iteration_index in iteration_indexes:
new_node = self._create_execution_node_copy(node, node_id, iteration_index)
- if iteration_path is not None:
- prepared_iteration_path = iteration_path
- if isinstance(node, IterateInvocation):
- prepared_iteration_path += (iteration_index,)
- self._state._prepared_registry().set_iteration_path(new_node.id, prepared_iteration_path)
- self._attach_execution_edges(new_node.id, new_edges)
- self._initialize_execution_node(new_node.id)
+ new_node_iteration_path = iteration_path
+ if new_node_iteration_path is None:
+ new_node_iteration_path = self._get_known_iteration_path(iteration_index, iteration_node_map)
+ elif isinstance(node, IterateInvocation):
+ new_node_iteration_path += (iteration_index,)
+ if new_node_iteration_path is not None:
+ self._state._prepared_registry().set_iteration_path(new_node.id, new_node_iteration_path)
+ attached_edges = self._attach_execution_edges(new_node.id, new_edges)
+ self._initialize_execution_node(new_node.id, attached_edges)
new_nodes.append(new_node.id)
return new_nodes
@@ -652,7 +799,7 @@ class _ExecutionMaterializer:
parent_iterators: list[tuple[str, str]],
execution_graph: nx.DiGraph,
) -> Optional[str]:
- prepared_iterator = next((node_id for node_id in prepared_nodes if node_id in prepared_iterator_nodes), None)
+ prepared_iterator = next((node_id for node_id in prepared_iterator_nodes if node_id in prepared_nodes), None)
if prepared_iterator is None:
return None
if self._matches_parent_iterators(prepared_iterator, parent_iterators, execution_graph):
@@ -677,8 +824,10 @@ class _ExecutionMaterializer:
graph: nx.DiGraph,
execution_graph: nx.DiGraph,
prepared_iterator_nodes: list[str],
+ prepared_nodes: Optional[set[str]] = None,
) -> Optional[str]:
- prepared_nodes = self._get_prepared_nodes_for_source(source_node_id)
+ if prepared_nodes is None:
+ prepared_nodes = self._get_prepared_nodes_for_source(source_node_id)
if len(prepared_nodes) == 1 and not prepared_iterator_nodes:
return next(iter(prepared_nodes))
@@ -775,6 +924,9 @@ class _ExecutionScheduler:
def _insert_ready_node(self, queue: Deque[str], exec_node_id: str) -> None:
exec_node_path = self._state._get_iteration_path(exec_node_id)
+ if not queue or self._state._get_iteration_path(queue[-1]) <= exec_node_path:
+ queue.append(exec_node_id)
+ return
for i, existing in enumerate(queue):
if self._state._get_iteration_path(existing) > exec_node_path:
queue.insert(i, exec_node_id)
@@ -785,6 +937,9 @@ class _ExecutionScheduler:
self._state._set_prepared_exec_state(exec_node_id, "executed")
self._state.executed.add(exec_node_id)
self._state.results[exec_node_id] = output
+ node = self._state.execution_graph.nodes[exec_node_id]
+ if isinstance(node, (IterateInvocation, CollectInvocation)):
+ node.collection = []
def _mark_source_node_complete(self, exec_node_id: str) -> None:
registry = self._state._prepared_registry()
@@ -822,6 +977,7 @@ class _ExecutionScheduler:
q.remove(exec_node_id)
except ValueError:
continue
+ self._state._ready_node_ids.discard(exec_node_id)
def enqueue_if_ready(self, exec_node_id: str) -> None:
"""Push exec_node_id to its class queue if unmet inputs == 0."""
@@ -829,10 +985,11 @@ class _ExecutionScheduler:
if self._should_skip_ready_enqueue(exec_node_id):
return
queue = self._get_ready_queue(exec_node_id)
- if exec_node_id in queue:
+ if exec_node_id in self._state._ready_node_ids:
return
self._state._set_prepared_exec_state(exec_node_id, "ready")
self._insert_ready_node(queue, exec_node_id)
+ self._state._ready_node_ids.add(exec_node_id)
def get_next_node(self) -> Optional[BaseInvocation]:
"""Gets the next ready node: FIFO within class, drain class before switching."""
@@ -841,6 +998,7 @@ class _ExecutionScheduler:
q = self._state._ready_queues.get(self._state._active_class)
while q:
exec_node_id = q.popleft()
+ self._state._ready_node_ids.discard(exec_node_id)
if exec_node_id not in self._state.executed:
return self._state.execution_graph.nodes[exec_node_id]
self._state._active_class = None
@@ -872,6 +1030,11 @@ class _ExecutionScheduler:
self._record_completed_node(exec_node_id, output)
self._mark_source_node_complete(exec_node_id)
self._release_downstream_nodes(exec_node_id)
+ if len(self._state.executed_history) == len(self._state.graph.nodes):
+ self._state.execution_graph._invalidate_edge_indexes()
+ self._state._ready_queues = {}
+ self._state._ready_node_ids = set()
+ self._state._active_class = None
class _ExecutionRuntime:
@@ -881,12 +1044,7 @@ class _ExecutionRuntime:
self._state = state
def _get_cached_iteration_path(self, exec_node_id: str) -> Optional[tuple[int, ...]]:
- registry = self._state._prepared_registry()
- metadata_iteration_path = registry.get_iteration_path(exec_node_id)
- if metadata_iteration_path is not None:
- return metadata_iteration_path
-
- return self._state._iteration_path_cache.get(exec_node_id)
+ return self._state._prepared_registry().get_iteration_path(exec_node_id)
def _get_iteration_source_node_id(self, exec_node_id: str) -> Optional[str]:
if exec_node_id not in self._state.prepared_source_mapping:
@@ -933,7 +1091,6 @@ class _ExecutionRuntime:
return tuple(path)
def _cache_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> tuple[int, ...]:
- self._state._iteration_path_cache[exec_node_id] = iteration_path
self._state._prepared_registry().set_iteration_path(exec_node_id, iteration_path)
return iteration_path
@@ -992,6 +1149,14 @@ class _ExecutionRuntime:
def _prepare_collect_inputs(self, node: "CollectInvocation", input_edges: list[Edge]) -> None:
node.collection = self._build_collect_collection(input_edges)
+ def _prepare_iterate_inputs(self, node: "IterateInvocation", input_edges: list[Edge]) -> None:
+ for edge in input_edges:
+ if edge.destination.field != COLLECTION_FIELD:
+ continue
+ source_output = self._state.results[edge.source.node_id]
+ object.__setattr__(node, COLLECTION_FIELD, getattr(source_output, edge.source.field))
+ return
+
def _prepare_if_inputs(self, node: IfInvocation, input_edges: list[Edge]) -> None:
selected_field = self._state._resolved_if_exec_branches.get(node.id)
allowed_fields = {"condition", selected_field} if selected_field is not None else {"condition"}
@@ -1016,6 +1181,10 @@ class _ExecutionRuntime:
def prepare_inputs(self, node: BaseInvocation) -> None:
input_edges = self._state.execution_graph._get_input_edges(node.id)
+ if isinstance(node, IterateInvocation):
+ self._prepare_iterate_inputs(node, input_edges)
+ return
+
if isinstance(node, CollectInvocation):
self._prepare_collect_inputs(node, input_edges)
return
@@ -1240,7 +1409,7 @@ class IterateInvocationOutput(BaseInvocationOutput):
# TODO: Fill this out and move to invocations
-@invocation("iterate", version="1.1.0")
+@invocation("iterate", version="1.1.0", use_cache=False)
class IterateInvocation(BaseInvocation):
"""Iterates over a list of items"""
@@ -1253,6 +1422,11 @@ class IterateInvocation(BaseInvocation):
"""Produces the outputs as values"""
return IterateInvocationOutput(item=self.collection[self.index], index=self.index, total=len(self.collection))
+ def get_event_invocation(self) -> "IterateInvocation":
+ event_invocation = self.model_copy()
+ event_invocation.collection = []
+ return event_invocation
+
@invocation_output("collect_output")
class CollectInvocationOutput(BaseInvocationOutput):
@@ -1261,7 +1435,7 @@ class CollectInvocationOutput(BaseInvocationOutput):
)
-@invocation("collect", version="1.1.0")
+@invocation("collect", version="1.1.0", use_cache=False)
class CollectInvocation(BaseInvocation):
"""Collects values into a collection"""
@@ -1283,6 +1457,11 @@ class CollectInvocation(BaseInvocation):
"""Invoke with provided services and return outputs."""
return CollectInvocationOutput(collection=copy.copy(self.collection))
+ def get_event_invocation(self) -> "CollectInvocation":
+ event_invocation = self.model_copy()
+ event_invocation.collection = []
+ return event_invocation
+
class AnyInvocation(BaseInvocation):
@classmethod
@@ -1327,6 +1506,90 @@ class AnyInvocationOutput(BaseInvocationOutput):
return {"oneOf": oneOf}
+_EdgeListMutationParams = ParamSpec("_EdgeListMutationParams")
+_EdgeListMutationResult = TypeVar("_EdgeListMutationResult")
+
+
+def _invalidates_edge_indexes(
+ method: Callable[Concatenate["_EdgeList", _EdgeListMutationParams], _EdgeListMutationResult],
+) -> Callable[Concatenate["_EdgeList", _EdgeListMutationParams], _EdgeListMutationResult]:
+ @wraps(method)
+ def wrapped(
+ self: "_EdgeList", *args: _EdgeListMutationParams.args, **kwargs: _EdgeListMutationParams.kwargs
+ ) -> _EdgeListMutationResult:
+ try:
+ return method(self, *args, **kwargs)
+ finally:
+ self._invalidate_indexes()
+
+ return wrapped
+
+
+class _EdgeList(list[Edge]):
+ """A graph-owned edge list that invalidates adjacency indexes after direct mutation."""
+
+ def __init__(self, edges: Iterable[Edge], owner: "Graph") -> None:
+ super().__init__(edges)
+ self._owner_ref = weakref.ref(owner)
+
+ def _invalidate_indexes(self) -> None:
+ owner_ref = getattr(self, "_owner_ref", None)
+ owner = owner_ref() if owner_ref is not None else None
+ if owner is not None:
+ owner._invalidate_edge_indexes()
+
+ def __getstate__(self) -> dict[str, Any]:
+ return {}
+
+ @_invalidates_edge_indexes
+ def append(self, edge: Edge) -> None:
+ super().append(edge)
+
+ @_invalidates_edge_indexes
+ def extend(self, edges: Iterable[Edge]) -> None:
+ super().extend(edges)
+
+ @_invalidates_edge_indexes
+ def insert(self, index: int, edge: Edge) -> None:
+ super().insert(index, edge)
+
+ @_invalidates_edge_indexes
+ def __setitem__(self, index: Any, value: Any) -> None:
+ super().__setitem__(index, value)
+
+ @_invalidates_edge_indexes
+ def __delitem__(self, index: Any) -> None:
+ super().__delitem__(index)
+
+ @_invalidates_edge_indexes
+ def __iadd__(self, edges: Iterable[Edge]):
+ return super().__iadd__(edges)
+
+ @_invalidates_edge_indexes
+ def __imul__(self, value: int):
+ return super().__imul__(value)
+
+ @_invalidates_edge_indexes
+ def clear(self) -> None:
+ super().clear()
+
+ @_invalidates_edge_indexes
+ def pop(self, index: int = -1) -> Edge:
+ return super().pop(index)
+
+ @_invalidates_edge_indexes
+ def remove(self, edge: Edge) -> None:
+ super().remove(edge)
+
+ @_invalidates_edge_indexes
+ def reverse(self) -> None:
+ super().reverse()
+
+ @_invalidates_edge_indexes
+ def sort(self, *, key=None, reverse: bool = False) -> None:
+ super().sort(key=key, reverse=reverse)
+
+
class Graph(BaseModel):
"""A validated invocation graph made of nodes and typed edges."""
@@ -1337,6 +1600,79 @@ class Graph(BaseModel):
description="The connections between nodes and their fields in this graph",
default_factory=list,
)
+ _input_edges_by_node: Optional[dict[str, list[Edge]]] = PrivateAttr(default=None)
+ _output_edges_by_node: Optional[dict[str, list[Edge]]] = PrivateAttr(default=None)
+
+ def _rebind_edge_list(self) -> None:
+ object.__setattr__(self, "edges", _EdgeList(self.edges, self))
+ self._invalidate_edge_indexes()
+
+ def model_post_init(self, __context: Any) -> None:
+ self._rebind_edge_list()
+
+ def model_copy(self, *, update: Optional[dict[str, Any]] = None, deep: bool = False) -> "Graph":
+ copied = super().model_copy(update=update, deep=deep)
+ copied._rebind_edge_list()
+ return copied
+
+ def __copy__(self) -> "Graph":
+ copied = super().__copy__()
+ copied._rebind_edge_list()
+ return copied
+
+ def __deepcopy__(self, memo: Optional[dict[int, Any]] = None) -> "Graph":
+ copied = super().__deepcopy__(memo)
+ copied._rebind_edge_list()
+ return copied
+
+ def __setstate__(self, state: dict[str, Any]) -> None:
+ super().__setstate__(state)
+ self._rebind_edge_list()
+
+ def __setattr__(self, name: str, value: Any) -> None:
+ if name == "edges":
+ value = _EdgeList(value, self)
+ super().__setattr__(name, value)
+ self._invalidate_edge_indexes()
+ return
+ super().__setattr__(name, value)
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, Graph):
+ return NotImplemented
+ return self.id == other.id and self.nodes == other.nodes and self.edges == other.edges
+
+ def _invalidate_edge_indexes(self) -> None:
+ self._input_edges_by_node = None
+ self._output_edges_by_node = None
+
+ def _ensure_edge_indexes(self) -> None:
+ if self._input_edges_by_node is not None and self._output_edges_by_node is not None:
+ return
+
+ input_edges_by_node: dict[str, list[Edge]] = {}
+ output_edges_by_node: dict[str, list[Edge]] = {}
+ for edge in self.edges:
+ input_edges_by_node.setdefault(edge.destination.node_id, []).append(edge)
+ output_edges_by_node.setdefault(edge.source.node_id, []).append(edge)
+ self._input_edges_by_node = input_edges_by_node
+ self._output_edges_by_node = output_edges_by_node
+
+ def _add_edge_to_indexes(self, edge: Edge) -> None:
+ if self._input_edges_by_node is not None:
+ self._input_edges_by_node.setdefault(edge.destination.node_id, []).append(edge)
+ if self._output_edges_by_node is not None:
+ self._output_edges_by_node.setdefault(edge.source.node_id, []).append(edge)
+
+ def _remove_edge_from_indexes(self, edge: Edge) -> None:
+ if self._input_edges_by_node is not None:
+ input_edges = self._input_edges_by_node.get(edge.destination.node_id)
+ if input_edges is not None:
+ input_edges.remove(edge)
+ if self._output_edges_by_node is not None:
+ output_edges = self._output_edges_by_node.get(edge.source.node_id)
+ if output_edges is not None:
+ output_edges.remove(edge)
def add_node(self, node: BaseInvocation) -> None:
"""Adds a node to a graph
@@ -1382,15 +1718,29 @@ class Graph(BaseModel):
def _add_edge(self, edge: Edge, allow_inputless_source_collector: bool) -> None:
self._validate_edge(edge, allow_inputless_source_collector)
if edge not in self.edges:
- self.edges.append(edge)
+ list.append(self.edges, edge)
+ self._add_edge_to_indexes(edge)
else:
raise InvalidEdgeError()
+ def _extend_edges_unchecked(self, edges: Iterable[Edge]) -> None:
+ """Adds trusted runtime edges without author-time graph validation.
+
+ This is only for execution edges derived from an already-validated source graph. Runtime materialization
+ preserves the source graph's direction and field connections, so repeating cycle, uniqueness, and type checks
+ for every expanded edge is redundant and prohibitively expensive for large iterator collections.
+ """
+ new_edges = list(edges)
+ list.extend(self.edges, new_edges)
+ for edge in new_edges:
+ self._add_edge_to_indexes(edge)
+
def delete_edge(self, edge: Edge) -> None:
"""Deletes an edge from a graph"""
try:
- self.edges.remove(edge)
+ list.remove(self.edges, edge)
+ self._remove_edge_from_indexes(edge)
except ValueError:
pass
@@ -1648,10 +1998,12 @@ class Graph(BaseModel):
def _get_input_edges(self, node_id: str, field: Optional[str] = None) -> list[Edge]:
"""Gets all input edges for a node. If field is provided, only edges to that field are returned."""
- edges = [e for e in self.edges if e.destination.node_id == node_id]
+ self._ensure_edge_indexes()
+ assert self._input_edges_by_node is not None
+ edges = self._input_edges_by_node.get(node_id, [])
if field is None:
- return edges
+ return list(edges)
filtered_edges = [e for e in edges if e.destination.field == field]
@@ -1659,10 +2011,12 @@ class Graph(BaseModel):
def _get_output_edges(self, node_id: str, field: Optional[str] = None) -> list[Edge]:
"""Gets all output edges for a node. If field is provided, only edges from that field are returned."""
- edges = [e for e in self.edges if e.source.node_id == node_id]
+ self._ensure_edge_indexes()
+ assert self._output_edges_by_node is not None
+ edges = self._output_edges_by_node.get(node_id, [])
if field is None:
- return edges
+ return list(edges)
filtered_edges = [e for e in edges if e.source.field == field]
@@ -2019,14 +2373,18 @@ class GraphExecutionState(BaseModel):
description="The map of original graph nodes to prepared nodes",
default_factory=dict,
)
+ prepared_iteration_paths: dict[str, tuple[int, ...]] = Field(
+ description="The iteration coordinates of each prepared execution node",
+ default_factory=dict,
+ )
# Ready queues grouped by node class name (internal only)
_ready_queues: dict[str, Deque[str]] = PrivateAttr(default_factory=dict)
+ _ready_node_ids: set[str] = PrivateAttr(default_factory=set)
# Current class being drained; stays until its queue empties
_active_class: Optional[str] = PrivateAttr(default=None)
# Optional priority; others follow in name order
ready_order: list[str] = Field(default_factory=list)
indegree: dict[str, int] = Field(default_factory=dict, description="Remaining unmet input count for exec nodes")
- _iteration_path_cache: dict[str, tuple[int, ...]] = PrivateAttr(default_factory=dict)
_if_branch_exclusive_sources: dict[str, dict[str, set[str]]] = PrivateAttr(default_factory=dict)
_resolved_if_exec_branches: dict[str, str] = PrivateAttr(default_factory=dict)
_prepared_exec_metadata: dict[str, _PreparedExecNodeMetadata] = PrivateAttr(default_factory=dict)
@@ -2044,6 +2402,7 @@ class GraphExecutionState(BaseModel):
self._prepared_exec_registry = _PreparedExecRegistry(
prepared_source_mapping=self.prepared_source_mapping,
source_prepared_mapping=self.source_prepared_mapping,
+ prepared_iteration_paths=self.prepared_iteration_paths,
metadata=self._prepared_exec_metadata,
)
return self._prepared_exec_registry
@@ -2115,8 +2474,8 @@ class GraphExecutionState(BaseModel):
def _reset_runtime_caches(self) -> None:
self._ready_queues = {}
+ self._ready_node_ids = set()
self._active_class = None
- self._iteration_path_cache = {}
self._if_branch_exclusive_sources = {}
self._resolved_if_exec_branches = {}
self._prepared_exec_metadata = {}
@@ -2131,7 +2490,10 @@ class GraphExecutionState(BaseModel):
for exec_node_id, source_node_id in self.prepared_source_mapping.items():
metadata = registry.get_metadata(exec_node_id)
metadata.source_node_id = source_node_id
- metadata.iteration_path = self._get_iteration_path(exec_node_id)
+ iteration_path = registry.get_iteration_path(exec_node_id)
+ if iteration_path is None:
+ iteration_path = self._get_iteration_path(exec_node_id)
+ metadata.iteration_path = iteration_path
if exec_node_id in self.executed:
metadata.state = "executed" if exec_node_id in self.results else "skipped"
elif self.indegree.get(exec_node_id) == 0:
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index e4c7058797..4207f81600 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -18687,7 +18687,7 @@
"ui_type": "IsIntermediate"
},
"use_cache": {
- "default": true,
+ "default": false,
"description": "Whether or not to use the cache",
"field_kind": "node_attribute",
"title": "Use Cache",
@@ -33219,6 +33219,17 @@
"title": "Source Prepared Mapping",
"description": "The map of original graph nodes to prepared nodes"
},
+ "prepared_iteration_paths": {
+ "additionalProperties": {
+ "items": {
+ "type": "integer"
+ },
+ "type": "array"
+ },
+ "type": "object",
+ "title": "Prepared Iteration Paths",
+ "description": "The iteration coordinates of each prepared execution node"
+ },
"ready_order": {
"items": {
"type": "string"
@@ -47385,7 +47396,7 @@
"ui_type": "IsIntermediate"
},
"use_cache": {
- "default": true,
+ "default": false,
"description": "Whether or not to use the cache",
"field_kind": "node_attribute",
"title": "Use Cache",
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index c413ccd7ab..7c960b6792 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -6706,7 +6706,7 @@ export type components = {
/**
* Use Cache
* @description Whether or not to use the cache
- * @default true
+ * @default false
*/
use_cache?: boolean;
/**
@@ -13384,6 +13384,13 @@ export type components = {
source_prepared_mapping: {
[key: string]: string[];
};
+ /**
+ * Prepared Iteration Paths
+ * @description The iteration coordinates of each prepared execution node
+ */
+ prepared_iteration_paths?: {
+ [key: string]: number[];
+ };
/** Ready Order */
ready_order?: string[];
/**
@@ -18714,7 +18721,7 @@ export type components = {
/**
* Use Cache
* @description Whether or not to use the cache
- * @default true
+ * @default false
*/
use_cache?: boolean;
/**
diff --git a/tests/app/services/session_queue/test_session_queue_status_event_isolation.py b/tests/app/services/session_queue/test_session_queue_status_event_isolation.py
index 56e66ff6aa..48c90a950a 100644
--- a/tests/app/services/session_queue/test_session_queue_status_event_isolation.py
+++ b/tests/app/services/session_queue/test_session_queue_status_event_isolation.py
@@ -7,14 +7,12 @@ so unredacted fields would let owner A learn user B's identifiers.
"""
import uuid
-from typing import Optional
import pytest
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
from invokeai.app.services.events.events_common import QueueItemStatusChangedEvent
from invokeai.app.services.invoker import Invoker
-from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem
from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue
from invokeai.app.services.shared.graph import Graph, GraphExecutionState
from tests.test_nodes import PromptTestInvocation, TestEventService
@@ -141,6 +139,25 @@ def test_event_redacts_other_users_current_item_identifiers(
assert a_event.queue_status.canceled == 1
+def test_get_queue_status_does_not_load_full_current_session(
+ session_queue: SqliteSessionQueue, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ item_id = _insert_queue_item(session_queue, user_id="user-a")
+ in_progress = session_queue.dequeue()
+ assert in_progress is not None and in_progress.item_id == item_id
+
+ def fail_get_current(queue_id: str):
+ raise AssertionError(f"Unexpected full current-item load for queue {queue_id}")
+
+ monkeypatch.setattr(session_queue, "get_current", fail_get_current)
+
+ status = session_queue.get_queue_status("default")
+
+ assert status.item_id == item_id
+ assert status.session_id == in_progress.session_id
+ assert status.batch_id == in_progress.batch_id
+
+
def test_event_preserves_owner_current_item_identifiers(
session_queue: SqliteSessionQueue, mock_invoker: Invoker
) -> None:
@@ -168,20 +185,11 @@ def test_event_preserves_owner_current_item_identifiers(
assert a_event.queue_status.completed == 1
-def test_event_redacts_when_current_item_disappears_between_reads(
+def test_event_redaction_uses_same_lightweight_snapshot(
session_queue: SqliteSessionQueue,
mock_invoker: Invoker,
- monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Regression: _set_queue_item_status reads get_current twice — once via
- get_queue_status (which embeds the in-progress item's identifiers into the
- SessionQueueStatus) and once again to decide whether to redact those
- identifiers. The two reads are not atomic. If user B is the in-progress
- item when the first read happens, and B then completes/cancels before the
- second read, the redaction guard sees current_item is None and skips
- scrubbing — leaving B's item_id, session_id, and batch_id in the event
- sent to user A. The fix must make the redaction decision derive from the
- same snapshot that supplied the embedded identifiers."""
+ """The status query must use one lightweight snapshot for identifiers and redaction."""
user_a = "user-a"
user_b = "user-b"
@@ -192,33 +200,11 @@ def test_event_redacts_when_current_item_disappears_between_reads(
assert in_progress is not None and in_progress.item_id == b_item_id
assert in_progress.user_id == user_b
- real_get_current = session_queue.get_current
- b_snapshot = real_get_current(queue_id="default")
- assert b_snapshot is not None and b_snapshot.user_id == user_b
-
- # Simulate the race: the read inside get_queue_status sees B's in-progress
- # item; the redaction read returns None as if B finished in between.
- call_count = {"n": 0}
-
- def racey_get_current(queue_id: str) -> Optional[SessionQueueItem]:
- call_count["n"] += 1
- if call_count["n"] == 1:
- return b_snapshot
- return None
-
- monkeypatch.setattr(session_queue, "get_current", racey_get_current)
-
event_bus: TestEventService = mock_invoker.services.events
event_bus.events.clear()
canceled = session_queue.cancel_queue_item(a_item_id)
assert canceled.user_id == user_a
- # The patched read must have been consulted at least once. The pre-fix
- # implementation made two reads (embedding + redaction) and leaked when
- # the second returned None; the fixed implementation makes a single read
- # whose snapshot drives both embedding and redaction. Either way, the
- # invariant below is the one that matters.
- assert call_count["n"] >= 1
a_event = _last_status_event_for_item(event_bus, a_item_id)
assert a_event.user_id == user_a
diff --git a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
index 8c17d71055..edf678f0df 100644
--- a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
+++ b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
@@ -150,6 +150,47 @@ def test_get_queue_item_round_trips_workflow_call_metadata(session_queue: Sqlite
assert queue_item.workflow_call_depth == 3
+def test_save_queue_item_session_does_not_reload_full_queue_item(
+ session_queue: SqliteSessionQueue, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ session = GraphExecutionState(graph=Graph())
+ item_id = _insert_queue_item(session_queue, session=session, status="pending")
+ session.errors["node"] = "updated"
+
+ def fail_get_queue_item(item_id: int):
+ raise AssertionError(f"Unexpected full queue item reload for {item_id}")
+
+ monkeypatch.setattr(session_queue, "get_queue_item", fail_get_queue_item)
+
+ session_queue.save_queue_item_session(item_id, session)
+
+ with session_queue._db.transaction() as cursor:
+ cursor.execute("SELECT session FROM session_queue WHERE item_id = ?", (item_id,))
+ row = cursor.fetchone()
+ assert row is not None
+ persisted = GraphExecutionState.model_validate_json(row[0])
+ assert persisted.errors == {"node": "updated"}
+
+
+def test_status_transition_reuses_loaded_queue_item(
+ session_queue: SqliteSessionQueue, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ session = GraphExecutionState(graph=Graph())
+ item_id = _insert_queue_item(session_queue, session=session, status="in_progress")
+ queue_item = session_queue.get_queue_item(item_id)
+
+ def fail_get_queue_item(item_id: int):
+ raise AssertionError(f"Unexpected full queue item reload for {item_id}")
+
+ monkeypatch.setattr(session_queue, "get_queue_item", fail_get_queue_item)
+
+ updated = session_queue.suspend_queue_item(item_id, queue_item=queue_item)
+
+ assert updated is queue_item
+ assert updated.status == "waiting"
+ assert updated.status_sequence == 1
+
+
def test_enqueue_workflow_call_child_persists_pending_child_queue_item(session_queue: SqliteSessionQueue) -> None:
parent_graph = Graph()
parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))
diff --git a/tests/app/services/shared/test_graph_execution_performance.py b/tests/app/services/shared/test_graph_execution_performance.py
new file mode 100644
index 0000000000..abdb659cd4
--- /dev/null
+++ b/tests/app/services/shared/test_graph_execution_performance.py
@@ -0,0 +1,180 @@
+"""Manual graph-execution performance benchmarks.
+
+These tests are marked slow and are excluded from normal pytest and CI runs. Run this benchmark with:
+
+ pytest -m slow -s tests/app/services/shared/test_graph_execution_performance.py
+"""
+
+from __future__ import annotations
+
+import gc
+import json
+import time
+import tracemalloc
+from dataclasses import asdict, dataclass
+from unittest.mock import Mock
+
+import pytest
+
+from invokeai.app.invocations.baseinvocation import InvocationContext
+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
+from invokeai.app.invocations.collections import RangeInvocation
+from invokeai.app.invocations.math import AddInvocation
+from invokeai.app.invocations.workflow_return import (
+ WorkflowReturnInvocation,
+ WorkflowReturnOutput,
+ WorkflowReturnValueInvocation,
+)
+from invokeai.app.services.shared.graph import (
+ CollectInvocation,
+ CollectInvocationOutput,
+ Graph,
+ GraphExecutionState,
+ IterateInvocation,
+)
+from tests.test_nodes import AnyTypeTestInvocation, create_edge
+
+ITEM_COUNT = 300
+CHILD_NODE_COUNT = 20
+
+
+@dataclass(frozen=True)
+class WorkflowCallBenchmarkResult:
+ items: int
+ child_nodes: int
+ calls: int
+ final_execution_nodes: int
+ final_session_json_bytes: int
+ total_seconds: float
+ boundary_restore_seconds: float
+ serialization_seconds: float
+ child_execution_seconds: float
+ traced_final_restore_seconds: float
+ traced_final_restore_live_bytes: int
+ traced_final_restore_peak_bytes: int
+
+
+def _build_child_graph(node_count: int) -> Graph:
+ if node_count < 3:
+ raise ValueError("The child workflow needs a value node, a return-value node, and a return node")
+
+ graph = Graph()
+ passthrough_node_count = node_count - 2
+ for index in range(passthrough_node_count):
+ node_id = f"child_{index}"
+ graph.add_node(AnyTypeTestInvocation(id=node_id, value=index if index == 0 else None))
+ if index:
+ graph.add_edge(create_edge(f"child_{index - 1}", "value", node_id, "value"))
+ graph.add_node(WorkflowReturnValueInvocation(id="child_return_value", key="value"))
+ graph.add_node(WorkflowReturnInvocation(id="child_return"))
+ graph.add_edge(create_edge(f"child_{passthrough_node_count - 1}", "value", "child_return_value", "value"))
+ graph.add_edge(create_edge("child_return_value", "value", "child_return", "values"))
+ return graph
+
+
+def _execute_child(session: GraphExecutionState) -> WorkflowReturnOutput:
+ context = Mock(InvocationContext)
+ while (invocation := session.next()) is not None:
+ session.complete(invocation.id, invocation.invoke(context))
+
+ prepared_return_id = next(iter(session.source_prepared_mapping["child_return"]))
+ output = session.results[prepared_return_id]
+ assert isinstance(output, WorkflowReturnOutput)
+ return output
+
+
+def _build_main_graph(item_count: int) -> Graph:
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=item_count, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="before_call", b=1))
+ graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="saved-workflow"))
+ graph.add_node(AnyTypeTestInvocation(id="after_call"))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "before_call", "a"))
+ graph.add_edge(create_edge("before_call", "value", "call", "saved_workflow_input::input::value"))
+ graph.add_edge(create_edge("call", "values", "after_call", "value"))
+ graph.add_edge(create_edge("after_call", "value", "collect", "item"))
+ return graph
+
+
+def _run_workflow_call_benchmark(item_count: int, child_node_count: int) -> WorkflowCallBenchmarkResult:
+ state = GraphExecutionState(graph=_build_main_graph(item_count))
+ child_graph = _build_child_graph(child_node_count)
+ context = Mock(InvocationContext)
+ calls = 0
+ boundary_restore_seconds = 0.0
+ serialization_seconds = 0.0
+ child_execution_seconds = 0.0
+ started = time.perf_counter()
+
+ while (invocation := state.next()) is not None:
+ if isinstance(invocation, CallSavedWorkflowInvocation):
+ child_started = time.perf_counter()
+ frame = state.build_workflow_call_frame(invocation.id, invocation.workflow_id)
+ child = state.create_child_workflow_execution_state(child_graph, frame)
+ child_output = _execute_child(child)
+ child_execution_seconds += time.perf_counter() - child_started
+
+ state.begin_waiting_on_workflow_call(frame)
+ state.attach_waiting_workflow_call_child_session(child)
+
+ serialization_started = time.perf_counter()
+ raw = state.model_dump_json(warnings=False, exclude_none=True)
+ serialization_seconds += time.perf_counter() - serialization_started
+
+ restore_started = time.perf_counter()
+ state = GraphExecutionState.model_validate_json(raw)
+ boundary_restore_seconds += time.perf_counter() - restore_started
+
+ state.end_waiting_on_workflow_call(status="completed")
+ state.complete(invocation.id, child_output)
+ calls += 1
+ else:
+ state.complete(invocation.id, invocation.invoke(context))
+
+ total_seconds = time.perf_counter() - started
+ final_session_json = state.model_dump_json(warnings=False, exclude_none=True)
+
+ prepared_collect_id = next(iter(state.source_prepared_mapping["collect"]))
+ collect_output = state.results[prepared_collect_id]
+ assert isinstance(collect_output, CollectInvocationOutput)
+ assert len(collect_output.collection) == item_count
+ assert calls == item_count
+ assert state.is_complete()
+
+ gc.collect()
+ tracemalloc.start()
+ try:
+ restore_started = time.perf_counter()
+ restored_state = GraphExecutionState.model_validate_json(final_session_json)
+ traced_final_restore_seconds = time.perf_counter() - restore_started
+ traced_final_restore_live_bytes, traced_final_restore_peak_bytes = tracemalloc.get_traced_memory()
+ assert restored_state.is_complete()
+ finally:
+ tracemalloc.stop()
+
+ return WorkflowCallBenchmarkResult(
+ items=item_count,
+ child_nodes=child_node_count,
+ calls=calls,
+ final_execution_nodes=len(state.execution_graph.nodes),
+ final_session_json_bytes=len(final_session_json.encode()),
+ total_seconds=round(total_seconds, 6),
+ boundary_restore_seconds=round(boundary_restore_seconds, 6),
+ serialization_seconds=round(serialization_seconds, 6),
+ child_execution_seconds=round(child_execution_seconds, 6),
+ traced_final_restore_seconds=round(traced_final_restore_seconds, 6),
+ traced_final_restore_live_bytes=traced_final_restore_live_bytes,
+ traced_final_restore_peak_bytes=traced_final_restore_peak_bytes,
+ )
+
+
+def test_iterated_call_saved_workflow_performance() -> None:
+ """Benchmark a 20-node saved workflow called once for each of 300 iterated items."""
+ result = _run_workflow_call_benchmark(item_count=ITEM_COUNT, child_node_count=CHILD_NODE_COUNT)
+
+ print("\nIterated Call Saved Workflow benchmark:")
+ print(json.dumps(asdict(result), indent=2, sort_keys=True))
diff --git a/tests/app/services/test_session_processor_callbacks.py b/tests/app/services/test_session_processor_callbacks.py
new file mode 100644
index 0000000000..bfca1b5062
--- /dev/null
+++ b/tests/app/services/test_session_processor_callbacks.py
@@ -0,0 +1,47 @@
+from contextlib import nullcontext
+from threading import Event
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner
+from invokeai.app.services.shared.graph import CollectInvocation, Graph, GraphExecutionState, IterateInvocation
+
+
[email protected]("invocation_type", [IterateInvocation, CollectInvocation])
+def test_after_run_node_callback_receives_control_node_inputs(monkeypatch: pytest.MonkeyPatch, invocation_type):
+ invocation = invocation_type(id="control", collection=[1, 2, 3])
+ callback_collections: list[list[int]] = []
+ callback_invocations = []
+ session = GraphExecutionState(graph=Graph())
+ session.execution_graph.add_node(invocation)
+ session._register_prepared_exec_node(invocation.id, "source")
+ session.indegree[invocation.id] = 0
+
+ services = SimpleNamespace(
+ configuration=SimpleNamespace(node_cache_size=0),
+ events=Mock(),
+ logger=Mock(),
+ performance_statistics=Mock(),
+ )
+ services.performance_statistics.collect_stats.return_value = nullcontext()
+ monkeypatch.setattr(
+ "invokeai.app.services.session_processor.session_processor_default.build_invocation_context",
+ lambda data, services, is_canceled: None,
+ )
+
+ def on_after_run_node(invocation, queue_item, output):
+ callback_invocations.append(invocation)
+ callback_collections.append(list(invocation.collection))
+
+ runner = DefaultSessionRunner(on_after_run_node_callbacks=[on_after_run_node])
+ runner.start(services=services, cancel_event=Event())
+ queue_item = Mock(session=session, session_id="session")
+
+ runner.run_node(invocation, queue_item)
+
+ assert callback_collections == [[1, 2, 3]]
+ assert callback_invocations == [invocation]
+ assert callback_invocations[0] is invocation
+ assert invocation.collection == []
diff --git a/tests/app/services/workflow_call_test_utils.py b/tests/app/services/workflow_call_test_utils.py
index 8923d050bd..34368cff03 100644
--- a/tests/app/services/workflow_call_test_utils.py
+++ b/tests/app/services/workflow_call_test_utils.py
@@ -934,23 +934,29 @@ class _DummySessionQueue:
self.session_updates.append((item_id, session))
return queue_item
- def suspend_queue_item(self, item_id: int):
+ def save_queue_item_session(self, item_id: int, session):
self._raise_if_not_found(item_id)
- queue_item = self._ensure_queue_item(item_id, None)
+ queue_item = self._ensure_queue_item(item_id, session)
+ queue_item.session = session
+ self.session_updates.append((item_id, session))
+
+ def suspend_queue_item(self, item_id: int, queue_item=None):
+ self._raise_if_not_found(item_id)
+ queue_item = queue_item or self._ensure_queue_item(item_id, None)
queue_item.status = "waiting"
self.waiting_item_ids.append(item_id)
return queue_item
- def resume_queue_item(self, item_id: int):
+ def resume_queue_item(self, item_id: int, queue_item=None):
self._raise_if_not_found(item_id)
- queue_item = self._ensure_queue_item(item_id, None)
+ queue_item = queue_item or self._ensure_queue_item(item_id, None)
queue_item.status = "pending"
self.resumed_item_ids.append(item_id)
return queue_item
- def complete_queue_item(self, item_id: int):
+ def complete_queue_item(self, item_id: int, queue_item=None):
self._raise_if_not_found(item_id)
- queue_item = self._ensure_queue_item(item_id, None)
+ queue_item = queue_item or self._ensure_queue_item(item_id, None)
queue_item.status = "completed"
self.completed_item_ids.append(item_id)
return queue_item
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index 95f1e41e0e..5242b54e9c 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -1,3 +1,5 @@
+from collections import defaultdict, deque
+from collections.abc import Iterator
from typing import Optional
from unittest.mock import Mock
@@ -30,6 +32,7 @@ from tests.test_nodes import (
AnyTypeTestInvocationOutput,
PromptCollectionTestInvocation,
PromptTestInvocation,
+ TestEventService,
TextToImageTestInvocation,
create_edge,
)
@@ -446,6 +449,347 @@ def test_graph_state_expands_iterator():
assert results == expected
+def test_graph_state_materialization_does_not_revalidate_execution_edges(monkeypatch: pytest.MonkeyPatch):
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=3, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "add", "a"))
+ graph.add_edge(create_edge("add", "value", "collect", "item"))
+
+ validate_edge_calls = 0
+ original_validate_edge = Graph._validate_edge
+
+ def track_validate_edge(self: Graph, edge):
+ nonlocal validate_edge_calls
+ validate_edge_calls += 1
+ return original_validate_edge(self, edge)
+
+ monkeypatch.setattr(Graph, "_validate_edge", track_validate_edge)
+
+ state = GraphExecutionState(graph=graph)
+ execute_all_nodes(state)
+
+ assert validate_edge_calls == 0
+ state.execution_graph.validate_self()
+
+
+def test_iterator_and_collector_do_not_use_invocation_cache_by_default():
+ assert IterateInvocation().use_cache is False
+ assert CollectInvocation().use_cache is False
+
+
+def test_materialized_control_nodes_disable_invocation_cache():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=3, step=1))
+ graph.add_node(IterateInvocation(id="iterate", use_cache=True))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_node(CollectInvocation(id="collect", use_cache=True))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "add", "a"))
+ graph.add_edge(create_edge("add", "value", "collect", "item"))
+ state = GraphExecutionState(graph=graph)
+
+ execute_all_nodes(state)
+
+ for source_node_id in ("iterate", "collect"):
+ for prepared_node_id in state.source_prepared_mapping[source_node_id]:
+ assert state.execution_graph.get_node(prepared_node_id).use_cache is False
+
+
+def test_iterator_and_collector_event_invocations_omit_collections():
+ iterator = IterateInvocation(collection=[1, 2, 3], index=1)
+ collector = CollectInvocation(collection=[1, 2, 3])
+
+ iterator_event_invocation = iterator.get_event_invocation()
+ collector_event_invocation = collector.get_event_invocation()
+
+ assert iterator_event_invocation is not iterator
+ assert iterator_event_invocation.collection == []
+ assert iterator_event_invocation.index == iterator.index
+ assert iterator.collection == [1, 2, 3]
+
+ assert collector_event_invocation is not collector
+ assert collector_event_invocation.collection == []
+ assert collector.collection == [1, 2, 3]
+
+
+def test_invocation_event_service_uses_compact_control_node_representation():
+ iterator = IterateInvocation(collection=[1, 2, 3], index=1)
+ queue_item = Mock(
+ queue_id="default",
+ item_id=1,
+ batch_id="batch",
+ origin="workflows",
+ destination=None,
+ user_id="system",
+ session_id="session",
+ session=Mock(prepared_source_mapping={iterator.id: "source"}),
+ )
+ events = TestEventService()
+
+ events.emit_invocation_started(queue_item, iterator)
+
+ assert len(events.events) == 1
+ event = events.events[0]
+ assert isinstance(event.invocation, IterateInvocation)
+ assert event.invocation.collection == []
+ assert iterator.collection == [1, 2, 3]
+
+
+def test_if_scheduler_does_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)
+ prepared_node = PromptTestInvocation(id="prepared", prompt="test")
+ state.execution_graph.add_node(prepared_node)
+ state._register_prepared_exec_node(prepared_node.id, "source")
+
+ def fail_get_iteration_path(self: GraphExecutionState, exec_node_id: str):
+ raise AssertionError(f"Unexpected iteration path lookup for {exec_node_id}")
+
+ monkeypatch.setattr(GraphExecutionState, "_get_iteration_path", fail_get_iteration_path)
+
+ assert state._if_scheduler().is_deferred_by_unresolved_if(prepared_node.id) is False
+
+
+def test_materializer_caches_iteration_paths_for_single_parent_chain(monkeypatch: pytest.MonkeyPatch):
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=3, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "add", "a"))
+ graph.add_edge(create_edge("add", "value", "collect", "item"))
+ state = GraphExecutionState(graph=graph)
+
+ def fail_build_iteration_path(exec_node_id: str, source_node_id: str):
+ raise AssertionError(f"Unexpected graph traversal for {exec_node_id} from {source_node_id}")
+
+ monkeypatch.setattr(state._runtime(), "_build_iteration_path", fail_build_iteration_path)
+
+ execute_all_nodes(state)
+
+
+def test_materializer_reuses_matching_parent_iteration_paths():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=1, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="left"))
+ graph.add_node(AddInvocation(id="right"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "left", "a"))
+ graph.add_edge(create_edge("iterate", "item", "right", "a"))
+ state = GraphExecutionState(graph=graph)
+ registry = state._prepared_registry()
+ registry.register("left-prepared", "left")
+ registry.register("right-prepared", "right")
+ registry.set_iteration_path("left-prepared", (2,))
+ registry.set_iteration_path("right-prepared", (2,))
+
+ iteration_path = state._materializer()._get_known_iteration_path(
+ -1,
+ [("left", "left-prepared"), ("right", "right-prepared")],
+ )
+
+ assert iteration_path == (2,)
+
+
+def test_materializer_does_not_merge_matching_paths_from_independent_iterators():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="left_range", start=0, stop=2, step=1))
+ graph.add_node(IterateInvocation(id="left_iterate"))
+ graph.add_node(RangeInvocation(id="right_range", start=0, stop=2, step=1))
+ graph.add_node(IterateInvocation(id="right_iterate"))
+ graph.add_node(AddInvocation(id="add"))
+ graph.add_edge(create_edge("left_range", "collection", "left_iterate", "collection"))
+ graph.add_edge(create_edge("right_range", "collection", "right_iterate", "collection"))
+ graph.add_edge(create_edge("left_iterate", "item", "add", "a"))
+ graph.add_edge(create_edge("right_iterate", "item", "add", "b"))
+ state = GraphExecutionState(graph=graph)
+
+ execute_all_nodes(state)
+
+ iteration_paths = {state._get_iteration_path(prepared_id) for prepared_id in state.source_prepared_mapping["add"]}
+ assert iteration_paths == {(0, 0), (0, 1), (1, 0), (1, 1)}
+
+
+def test_materializer_indexes_prepared_nodes_once_per_source(monkeypatch: pytest.MonkeyPatch):
+ item_count = 24
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=item_count, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "add", "a"))
+ graph.add_edge(create_edge("add", "value", "collect", "item"))
+ state = GraphExecutionState(graph=graph)
+ materializer_type = type(state._materializer())
+ original_get_prepared_nodes = materializer_type._get_prepared_nodes_for_source
+ calls_by_source: defaultdict[str, int] = defaultdict(int)
+
+ def track_get_prepared_nodes(self, source_node_id: str):
+ calls_by_source[source_node_id] += 1
+ return original_get_prepared_nodes(self, source_node_id)
+
+ monkeypatch.setattr(materializer_type, "_get_prepared_nodes_for_source", track_get_prepared_nodes)
+
+ execute_all_nodes(state)
+
+ assert calls_by_source["iterate"] <= 2
+ assert calls_by_source["add"] <= 2
+
+
+def test_materializer_uses_iteration_path_index_for_loop_body(monkeypatch: pytest.MonkeyPatch):
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=8, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="first_add", b=1))
+ graph.add_node(AddInvocation(id="second_add", b=1))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "first_add", "a"))
+ graph.add_edge(create_edge("first_add", "value", "second_add", "a"))
+ graph.add_edge(create_edge("second_add", "value", "collect", "item"))
+ state = GraphExecutionState(graph=graph)
+ materializer_type = type(state._materializer())
+
+ def fail_matches_parent_iterators(*args, **kwargs):
+ raise AssertionError("Known iteration paths should not require execution-graph path searches")
+
+ monkeypatch.setattr(materializer_type, "_matches_parent_iterators", fail_matches_parent_iterators)
+
+ execute_all_nodes(state)
+
+ prepared_collect_id = next(iter(state.source_prepared_mapping["collect"]))
+ assert state.results[prepared_collect_id].collection == list(range(2, 10))
+
+
+def test_materializer_yields_parent_iteration_mappings_lazily():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=3, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "add", "a"))
+ state = GraphExecutionState(graph=graph)
+
+ invoke_next(state)
+ iterate_node = state.next()
+ assert isinstance(iterate_node, IterateInvocation)
+
+ mappings = state._materializer()._get_parent_iteration_mappings("add", graph.nx_graph_flat())
+
+ assert isinstance(mappings, Iterator)
+ assert len(next(mappings)) == 1
+
+
+def test_graph_caches_edge_adjacency_and_updates_it_incrementally():
+ class CountingEdges(list):
+ def __init__(self, edges):
+ super().__init__(edges)
+ self.iterations = 0
+
+ def __iter__(self):
+ self.iterations += 1
+ return super().__iter__()
+
+ graph = Graph()
+ graph.add_node(PromptTestInvocation(id="source", prompt="test"))
+ graph.add_node(PromptTestInvocation(id="first"))
+ graph.add_node(PromptTestInvocation(id="second"))
+ first_edge = create_edge("source", "prompt", "first", "prompt")
+ second_edge = create_edge("source", "prompt", "second", "prompt")
+ graph.add_edge(first_edge)
+ counting_edges = CountingEdges(graph.edges)
+ object.__setattr__(graph, "edges", counting_edges)
+ graph._invalidate_edge_indexes()
+
+ assert graph._get_input_edges("first") == [first_edge]
+ assert graph._get_input_edges("first") == [first_edge]
+ assert counting_edges.iterations == 1
+
+ graph._extend_edges_unchecked([second_edge])
+ assert graph._get_input_edges("second") == [second_edge]
+ assert graph._get_output_edges("source") == [first_edge, second_edge]
+ assert counting_edges.iterations == 1
+
+ graph.delete_edge(first_edge)
+ assert graph._get_input_edges("first") == []
+ assert graph._get_output_edges("source") == [second_edge]
+ assert counting_edges.iterations == 1
+
+
+def test_ready_queue_does_not_scan_for_duplicate_nodes():
+ class NoMembershipScanDeque(deque):
+ def __contains__(self, value):
+ raise AssertionError("Ready queue membership must use the scheduler index")
+
+ state = GraphExecutionState(graph=Graph())
+ prepared_node = PromptTestInvocation(id="prepared", prompt="test")
+ state.execution_graph.add_node(prepared_node)
+ state._register_prepared_exec_node(prepared_node.id, "source")
+ state._prepared_registry().set_iteration_path(prepared_node.id, ())
+ state.indegree[prepared_node.id] = 0
+ class_name = state._type_key(prepared_node)
+ state._ready_queues[class_name] = NoMembershipScanDeque()
+
+ state._enqueue_if_ready(prepared_node.id)
+ state._enqueue_if_ready(prepared_node.id)
+
+ assert list(state._ready_queues[class_name]) == [prepared_node.id]
+
+
+def test_iterator_reuses_collection_input_until_completed():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=3, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ state = GraphExecutionState(graph=graph)
+
+ range_node, range_output = invoke_next(state)
+ assert range_node is not None
+ assert range_output is not None
+
+ iterate_node = state.next()
+ assert isinstance(iterate_node, IterateInvocation)
+ assert iterate_node.collection is range_output.collection
+
+ iterate_output = iterate_node.invoke(Mock(InvocationContext))
+ state.complete(iterate_node.id, iterate_output)
+
+ assert iterate_output.item == 0
+ assert iterate_node.collection == []
+
+
+def test_completed_collector_releases_input_collection_but_preserves_results():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=3, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "add", "a"))
+ graph.add_edge(create_edge("add", "value", "collect", "item"))
+ state = GraphExecutionState(graph=graph)
+
+ execute_all_nodes(state)
+
+ prepared_collect_id = next(iter(state.source_prepared_mapping["collect"]))
+ prepared_collect = state.execution_graph.get_node(prepared_collect_id)
+ assert isinstance(prepared_collect, CollectInvocation)
+ assert prepared_collect.collection == []
+ assert state.results[prepared_collect_id].collection == [1, 2, 3]
+ assert {state.results[node_id].value for node_id in state.source_prepared_mapping["add"]} == {1, 2, 3}
+ assert state.execution_graph._input_edges_by_node is None
+ assert state.execution_graph._output_edges_by_node is None
+ assert state._ready_node_ids == set()
+
+
def test_graph_state_collects():
graph = Graph()
test_prompts = ["Banana sushi", "Cat sushi"]
@@ -552,6 +896,62 @@ def test_graph_state_resumes_partially_executed_session_after_json_round_trip():
assert resumed.results[prepared_collect_id].collection == [2, 3, 4, 5]
+def test_graph_state_round_trip_reuses_persisted_iteration_paths(monkeypatch: pytest.MonkeyPatch):
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=24, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "add", "a"))
+ graph.add_edge(create_edge("add", "value", "collect", "item"))
+
+ state = GraphExecutionState(graph=graph)
+ for _ in range(8):
+ invocation, output = invoke_next(state)
+ assert invocation is not None
+ assert output is not None
+
+ raw = state.model_dump_json(warnings=False, exclude_none=True)
+ runtime_type = type(state._runtime())
+
+ def fail_build_iteration_path(self, exec_node_id: str, source_node_id: str):
+ raise AssertionError(f"Unexpected graph traversal for {exec_node_id} from {source_node_id}")
+
+ monkeypatch.setattr(runtime_type, "_build_iteration_path", fail_build_iteration_path)
+
+ resumed = TypeAdapter(GraphExecutionState).validate_json(raw, strict=False)
+
+ assert all(
+ resumed._get_iteration_path(exec_node_id) is not None for exec_node_id in resumed.prepared_source_mapping
+ )
+
+
+def test_graph_state_round_trip_rebuilds_iteration_paths_for_legacy_session():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=4, step=1))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "add", "a"))
+
+ state = GraphExecutionState(graph=graph)
+ for _ in range(3):
+ invocation, output = invoke_next(state)
+ assert invocation is not None
+ assert output is not None
+
+ legacy_payload = state.model_dump(mode="json", warnings=False, exclude_none=True)
+ legacy_payload.pop("prepared_iteration_paths")
+
+ resumed = TypeAdapter(GraphExecutionState).validate_python(legacy_payload, strict=False)
+
+ assert all(
+ resumed._get_iteration_path(exec_node_id) is not None for exec_node_id in resumed.prepared_source_mapping
+ )
+ assert execute_all_nodes(resumed)
+
+
def test_if_graph_state_resumes_resolved_branch_after_json_round_trip():
graph = Graph()
graph.add_node(BooleanInvocation(id="condition", value=True))
diff --git a/tests/test_node_graph.py b/tests/test_node_graph.py
index f8a826b4e4..64e652a61d 100644
--- a/tests/test_node_graph.py
+++ b/tests/test_node_graph.py
@@ -1,5 +1,8 @@
+import copy
+import pickle
+
import pytest
-from pydantic import TypeAdapter
+from pydantic import TypeAdapter, ValidationError
from pydantic.json_schema import models_json_schema
from invokeai.app.invocations.baseinvocation import (
@@ -558,6 +561,105 @@ def test_graph_invalid_with_invalid_connection():
assert g.is_valid() is False
+def test_graph_edge_indexes_follow_direct_edge_list_mutation():
+ graph = Graph()
+ range_node = PromptCollectionTestInvocation(id="range", collection=["one"])
+ iterate_node = IterateInvocation(id="iterate")
+ graph.add_node(range_node)
+ graph.add_node(iterate_node)
+ graph.add_edge(create_edge("range", "collection", "iterate", "collection"))
+
+ assert len(graph._get_input_edges("iterate")) == 1
+
+ graph.edges.clear()
+
+ assert graph._get_input_edges("iterate") == []
+ with pytest.raises(InvalidEdgeError):
+ graph.validate_self()
+
+
+def test_graph_edge_indexes_follow_edge_list_replacement():
+ edge = create_edge("source", "value", "destination", "value")
+ graph = Graph(edges=[edge])
+ assert graph._get_output_edges("source") == [edge]
+
+ graph.edges = []
+
+ assert graph._get_output_edges("source") == []
+
+
+def test_graph_edge_indexes_follow_partially_failed_edge_list_mutation():
+ first_edge = create_edge("source", "value", "first", "value")
+ second_edge = create_edge("source", "value", "second", "value")
+ graph = Graph(edges=[first_edge])
+ graph._get_output_edges("source")
+
+ def failing_edges():
+ yield second_edge
+ raise RuntimeError("failed while extending edges")
+
+ with pytest.raises(RuntimeError):
+ graph.edges.extend(failing_edges())
+
+ assert graph._get_output_edges("source") == [first_edge, second_edge]
+
+
+def test_graph_copy_rebinds_edge_list_invalidation():
+ edge = create_edge("source", "value", "destination", "value")
+ original = Graph(edges=[edge])
+ copied = original.model_copy()
+ copied._get_output_edges("source")
+
+ copied.edges.clear()
+
+ assert copied._get_output_edges("source") == []
+ assert original._get_output_edges("source") == [edge]
+
+
[email protected]("copy_graph", [copy.copy, copy.deepcopy])
+def test_graph_python_copy_rebinds_edge_list_invalidation(copy_graph):
+ edge = create_edge("source", "value", "destination", "value")
+ original = Graph(edges=[edge])
+ copied = copy_graph(original)
+ copied._get_output_edges("source")
+
+ copied.edges.clear()
+
+ assert copied._get_output_edges("source") == []
+ assert original._get_output_edges("source") == [edge]
+
+
+def test_graph_pickle_rebinds_edge_list_invalidation():
+ edge = create_edge("source", "value", "destination", "value")
+ graph = Graph(edges=[edge])
+
+ restored = pickle.loads(pickle.dumps(graph))
+ restored._get_output_edges("source")
+ restored.edges.clear()
+
+ assert restored._get_output_edges("source") == []
+
+
+def test_graph_edges_cannot_be_mutated_after_indexing():
+ edge = create_edge("source", "value", "destination", "value")
+ graph = Graph(edges=[edge])
+ graph._get_output_edges("source")
+
+ with pytest.raises(ValidationError):
+ edge.source.node_id = "different-source"
+
+ assert graph._get_output_edges("source") == [edge]
+
+
+def test_graph_equality_ignores_adjacency_cache_state():
+ left = Graph(id="same")
+ right = Graph(id="same")
+
+ left._get_input_edges("missing")
+
+ assert left == right
+
+
def test_graph_gets_networkx_graph():
g = Graph()
n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi")