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.

perf(execution): isolate transient runtime copy state

JPPhotob815253a05a1
diff --git a/invokeai/app/services/shared/execution_engine/primitives.py b/invokeai/app/services/shared/execution_engine/primitives.py
index 2c31e3a0d2..afdde2307c 100644
--- a/invokeai/app/services/shared/execution_engine/primitives.py
+++ b/invokeai/app/services/shared/execution_engine/primitives.py
@@ -345,10 +345,13 @@ class StreamBuffer(_InternalModel, Generic[T]):
*,
value: Any = _MISSING,
sequence: int | None = None,
+ trusted: bool = False,
) -> StreamData[T] | StreamEnd:
if isinstance(event, StreamData):
if value is not _MISSING or sequence is not None:
raise TypeError("event object cannot be combined with value or sequence")
+ if trusted:
+ return event
return self._make_data_event(event.sequence, event.value)
if isinstance(event, StreamEnd):
if value is not _MISSING or sequence is not None:
@@ -378,11 +381,16 @@ class StreamBuffer(_InternalModel, Generic[T]):
*,
value: Any = _MISSING,
sequence: int | None = None,
+ trusted: bool = False,
) -> bool:
- """Accept one event atomically; return false for exact retries."""
+ """Accept one event atomically; return false for exact retries.
+
+ ``trusted`` is reserved for rehydration of values already decoded from a JSON snapshot. Normal engine
+ inputs must use the default validated path.
+ """
with self._lock:
- candidate = self._coerce_event(event, value=value, sequence=sequence)
+ candidate = self._coerce_event(event, value=value, sequence=sequence, trusted=trusted)
existing = self.events[candidate.sequence] if candidate.sequence < len(self.events) else None
if existing is not None:
if existing == candidate:
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 8ad5f38df5..b2e9be6726 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -199,6 +199,89 @@ def _hide_execution_state_runtime_fields(schema: JsonSchemaValue) -> None:
schema["required"] = [field_name for field_name in _EXECUTION_STATE_REQUIRED_FIELDS if field_name in properties]
+class _GraphExecutionStateRuntime:
+ """Process-local execution state kept behind one pydantic private attribute."""
+
+ __slots__ = (
+ "ready_queues",
+ "ready_node_ids",
+ "active_class",
+ "resolved_if_exec_branches",
+ "pending_if_exec_nodes",
+ "if_branch_sources_cache",
+ "if_activation_dependencies_by_source",
+ "if_activation_dependencies_by_exec",
+ "prepared_if_exec_ids_by_source_and_frame",
+ "prepared_if_exec_frames_by_source",
+ "prepared_if_exec_indexed_sources",
+ "prepared_exec_metadata",
+ "prepared_exec_registry",
+ "if_activation_controller_instance",
+ "execution_materializer",
+ "generic_for_planner",
+ "execution_scheduler",
+ "execution_runtime",
+ "for_parent_iteration_paths_cache",
+ "all_for_contexts_finalized_cache",
+ "prepared_for_index",
+ "final_prepared_for_index",
+ "prepared_for_index_by_exec",
+ "source_graph_flat",
+ "execution_graph_flat",
+ "completed_source_ids_cache",
+ "unexecuted_prepared_counts",
+ "for_source_by_return_id",
+ "apply_transaction",
+ "generic_execution_runtime",
+ "generic_graph_scheduler",
+ "generic_child_dependencies",
+ "pending_lifecycle_execution_nodes",
+ "execution_effects_persisted",
+ "legacy_execution_snapshot",
+ "legacy_snapshot_loaded",
+ )
+
+ def __init__(self) -> None:
+ self.ready_queues: dict[str, Deque[str]] = {}
+ self.ready_node_ids: set[str] = set()
+ self.active_class: Optional[str] = None
+ self.resolved_if_exec_branches: dict[str, str] = {}
+ self.pending_if_exec_nodes: set[str] = set()
+ self.if_branch_sources_cache: dict[tuple[str, str], frozenset[str]] = {}
+ self.if_activation_dependencies_by_source: dict[
+ tuple[str, tuple[int, ...]], tuple[ActivationDependency, ...]
+ ] = {}
+ self.if_activation_dependencies_by_exec: dict[str, tuple[ActivationDependency, ...]] = {}
+ self.prepared_if_exec_ids_by_source_and_frame: dict[tuple[str, tuple[int, ...]], tuple[str, ...]] = {}
+ self.prepared_if_exec_frames_by_source: dict[str, tuple[tuple[int, ...], ...]] = {}
+ self.prepared_if_exec_indexed_sources: set[str] = set()
+ self.prepared_exec_metadata: dict[str, _PreparedExecNodeMetadata] = {}
+ self.prepared_exec_registry: Optional[_PreparedExecRegistry] = None
+ self.if_activation_controller_instance: Optional[_IfActivationController] = None
+ self.execution_materializer: Optional[_ExecutionMaterializer] = None
+ self.generic_for_planner: Optional[_GenericForPlanner] = None
+ self.execution_scheduler: Optional[_ExecutionScheduler | _GenericGraphSchedulerAdapter] = None
+ self.execution_runtime: Optional[_ExecutionRuntime] = None
+ self.for_parent_iteration_paths_cache: dict[str, set[tuple[int, ...]]] = {}
+ self.all_for_contexts_finalized_cache: dict[str, bool] = {}
+ self.prepared_for_index: Optional[dict[tuple[str, tuple[int, ...]], str]] = None
+ self.final_prepared_for_index: Optional[dict[tuple[str, tuple[int, ...]], str]] = None
+ self.prepared_for_index_by_exec: dict[str, tuple[str, tuple[int, ...], tuple[int, ...]]] = {}
+ self.source_graph_flat: Any | None = None
+ self.execution_graph_flat: Any | None = None
+ self.completed_source_ids_cache: Optional[set[str]] = None
+ self.unexecuted_prepared_counts: Optional[dict[str, int]] = None
+ self.for_source_by_return_id: Optional[dict[str, str]] = None
+ self.apply_transaction: Optional[_ApplyTransaction] = None
+ self.generic_execution_runtime: Optional[ExecutionEngineRuntime] = None
+ self.generic_graph_scheduler: Optional[_GenericGraphSchedulerAdapter] = None
+ self.generic_child_dependencies: dict[str, ChildDependencyRecord] = {}
+ self.pending_lifecycle_execution_nodes: set[str] = set()
+ self.execution_effects_persisted = False
+ self.legacy_execution_snapshot = True
+ self.legacy_snapshot_loaded = False
+
+
class GraphExecutionState(BaseModel):
"""Tracks source-graph expansion, execution progress, and runtime results."""
@@ -294,99 +377,75 @@ class GraphExecutionState(BaseModel):
description="Durable generic child dependency records",
exclude=True,
)
- # 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)
+ # All process-local runtime state is kept behind this single private attribute.
+ _runtime_state: _GraphExecutionStateRuntime = PrivateAttr(default_factory=_GraphExecutionStateRuntime)
# 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")
- _resolved_if_exec_branches: dict[str, str] = PrivateAttr(default_factory=dict)
- _pending_if_exec_nodes: set[str] = PrivateAttr(default_factory=set)
- _if_branch_sources_cache: dict[tuple[str, str], frozenset[str]] = PrivateAttr(default_factory=dict)
- _if_activation_dependencies_by_source: dict[tuple[str, tuple[int, ...]], tuple[ActivationDependency, ...]] = (
- PrivateAttr(default_factory=dict)
- )
- _if_activation_dependencies_by_exec: dict[str, tuple[ActivationDependency, ...]] = PrivateAttr(default_factory=dict)
- _prepared_if_exec_ids_by_source_and_frame: dict[tuple[str, tuple[int, ...]], tuple[str, ...]] = PrivateAttr(
- default_factory=dict
- )
- _prepared_if_exec_frames_by_source: dict[str, tuple[tuple[int, ...], ...]] = PrivateAttr(default_factory=dict)
- _prepared_if_exec_indexed_sources: set[str] = PrivateAttr(default_factory=set)
- _prepared_exec_metadata: dict[str, _PreparedExecNodeMetadata] = PrivateAttr(default_factory=dict)
- _prepared_exec_registry: Optional[_PreparedExecRegistry] = PrivateAttr(default=None)
- _if_activation_controller_instance: Optional[_IfActivationController] = PrivateAttr(default=None)
- _execution_materializer: Optional[_ExecutionMaterializer] = PrivateAttr(default=None)
- _generic_for_planner: Optional[_GenericForPlanner] = 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)
- _prepared_for_index: Optional[dict[tuple[str, tuple[int, ...]], str]] = PrivateAttr(default=None)
- _final_prepared_for_index: Optional[dict[tuple[str, tuple[int, ...]], str]] = PrivateAttr(default=None)
- _prepared_for_index_by_exec: dict[str, tuple[str, tuple[int, ...], tuple[int, ...]]] = PrivateAttr(
- default_factory=dict
- )
- _source_graph_flat: Any | None = PrivateAttr(default=None)
- _execution_graph_flat: Any | None = PrivateAttr(default=None)
- _completed_source_ids_cache: Optional[set[str]] = PrivateAttr(default=None)
- _unexecuted_prepared_counts: Optional[dict[str, int]] = PrivateAttr(default=None)
- _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)
- _pending_lifecycle_execution_nodes: set[str] = PrivateAttr(default_factory=set)
- _execution_effects_persisted: bool = PrivateAttr(default=False)
- _legacy_execution_snapshot: bool = PrivateAttr(default=True)
- _legacy_snapshot_loaded: bool = PrivateAttr(default=False)
+
+ def model_copy(self, *, update: Optional[dict[str, Any]] = None, deep: bool = False) -> "GraphExecutionState":
+ copied = super().model_copy(update=update, deep=deep)
+ if not deep:
+ copied.__pydantic_private__["_runtime_state"] = copy.copy(self.__pydantic_private__["_runtime_state"])
+ return copied
+
+ def __copy__(self) -> "GraphExecutionState":
+ copied = super().__copy__()
+ copied.__pydantic_private__["_runtime_state"] = copy.copy(self.__pydantic_private__["_runtime_state"])
+ return copied
def _tx_record_once(self, key: tuple[Any, ...], undo: Callable[[], None]) -> None:
- if self._apply_transaction is not None:
- self._apply_transaction.record_once(key, undo)
+ transaction = self.__pydantic_private__["_runtime_state"].apply_transaction
+ if transaction is not None:
+ transaction.record_once(key, undo)
def _tx_record(self, undo: Callable[[], None]) -> None:
- if self._apply_transaction is not None:
- self._apply_transaction.record(undo)
+ transaction = self.__pydantic_private__["_runtime_state"].apply_transaction
+ if transaction is not None:
+ transaction.record(undo)
def _tx_set_mapping(self, mapping: dict[Any, Any], key: Any, value: Any) -> None:
- if self._apply_transaction is not None:
+ transaction = self.__pydantic_private__["_runtime_state"].apply_transaction
+ if transaction is not None:
marker = ("mapping", id(mapping), key)
if key in mapping:
old_value = mapping[key]
- self._tx_record_once(marker, lambda: mapping.__setitem__(key, old_value))
+ transaction.record_once(marker, lambda: mapping.__setitem__(key, old_value))
else:
- self._tx_record_once(marker, lambda: mapping.pop(key, None))
+ transaction.record_once(marker, lambda: mapping.pop(key, None))
mapping[key] = value
def _tx_pop_mapping(self, mapping: dict[Any, Any], key: Any) -> None:
if key not in mapping:
return
old_value = mapping[key]
- if self._apply_transaction is not None:
- self._tx_record_once(("mapping", id(mapping), key), lambda: mapping.__setitem__(key, old_value))
+ transaction = self.__pydantic_private__["_runtime_state"].apply_transaction
+ if transaction is not None:
+ transaction.record_once(("mapping", id(mapping), key), lambda: mapping.__setitem__(key, old_value))
mapping.pop(key, None)
def _tx_set_attr(self, obj: Any, name: str, value: Any) -> None:
- if self._apply_transaction is not None:
+ transaction = self.__pydantic_private__["_runtime_state"].apply_transaction
+ if transaction is not None:
old_value = getattr(obj, name)
- self._tx_record_once(("attr", id(obj), name), lambda: setattr(obj, name, old_value))
+ transaction.record_once(("attr", id(obj), name), lambda: setattr(obj, name, old_value))
setattr(obj, name, value)
def _tx_add_set(self, values: set[Any], value: Any) -> None:
- if self._apply_transaction is not None:
+ transaction = self.__pydantic_private__["_runtime_state"].apply_transaction
+ if transaction is not None:
existed = value in values
- self._tx_record_once(
+ transaction.record_once(
("set", id(values), value),
lambda: None if existed else values.discard(value),
)
values.add(value)
def _tx_discard_set(self, values: set[Any], value: Any) -> None:
- if self._apply_transaction is not None:
+ transaction = self.__pydantic_private__["_runtime_state"].apply_transaction
+ if transaction is not None:
existed = value in values
- self._tx_record_once(
+ transaction.record_once(
("set", id(values), value),
lambda: values.add(value) if existed else None,
)
@@ -469,16 +528,17 @@ class GraphExecutionState(BaseModel):
return node_obj.__class__.__name__
def _prepared_registry(self) -> _PreparedExecRegistry:
- if self._prepared_exec_registry is None:
- self._prepared_exec_registry = _PreparedExecRegistry(
+ runtime = self.__pydantic_private__["_runtime_state"]
+ if runtime.prepared_exec_registry is None:
+ runtime.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,
+ metadata=runtime.prepared_exec_metadata,
on_iteration_path_change=self._invalidate_loop_caches_for_exec_node,
state=self,
)
- return self._prepared_exec_registry
+ return runtime.prepared_exec_registry
def _prepared_if_exec_ids(self, source_node_id: str, iteration_path: tuple[int, ...]) -> tuple[str, ...]:
"""Return prepared If executions for one source/frame without rescanning them per dependency check."""
@@ -510,9 +570,10 @@ class GraphExecutionState(BaseModel):
return self._if_activation_controller_instance
def _get_source_graph_flat(self) -> Any:
- if self._source_graph_flat is None:
- self._source_graph_flat = self.graph.nx_graph_flat()
- return self._source_graph_flat
+ runtime = self.__pydantic_private__["_runtime_state"]
+ if runtime.source_graph_flat is None:
+ runtime.source_graph_flat = self.graph.nx_graph_flat()
+ return runtime.source_graph_flat
def _get_fresh_if_nodes(self) -> tuple[IfInvocation, ...]:
return graph_if_dependencies._get_fresh_if_nodes(self)
@@ -541,26 +602,29 @@ class GraphExecutionState(BaseModel):
return graph_if_runtime._is_source_inactive(self, source_node_id, iteration_path)
def _get_execution_graph_flat(self) -> Any:
- if self._execution_graph_flat is None:
- self._execution_graph_flat = self.execution_graph.nx_graph_flat()
- return self._execution_graph_flat
+ runtime = self.__pydantic_private__["_runtime_state"]
+ if runtime.execution_graph_flat is None:
+ runtime.execution_graph_flat = self.execution_graph.nx_graph_flat()
+ return runtime.execution_graph_flat
def _add_execution_graph_node(self, node_id: str) -> None:
- if self._execution_graph_flat is not None:
- self._execution_graph_flat.add_node(node_id)
+ execution_graph_flat = self.__pydantic_private__["_runtime_state"].execution_graph_flat
+ if execution_graph_flat is not None:
+ execution_graph_flat.add_node(node_id)
def _add_execution_graph_edges(self, edges: Iterable[Edge]) -> None:
- if self._execution_graph_flat is not None:
- self._execution_graph_flat.add_edges_from(
+ execution_graph_flat = self.__pydantic_private__["_runtime_state"].execution_graph_flat
+ if execution_graph_flat is not None:
+ execution_graph_flat.add_edges_from(
(edge.source.node_id, edge.destination.node_id) for edge in edges if edge.type == "default"
)
def _invalidate_execution_graph_flat(self) -> None:
- self._execution_graph_flat = None
+ self.__pydantic_private__["_runtime_state"].execution_graph_flat = None
def _mark_source_executed(self, source_node_id: str) -> None:
self._tx_add_set(self.executed, source_node_id)
- self._completed_source_ids_cache = None
+ self.__pydantic_private__["_runtime_state"].completed_source_ids_cache = None
self._tx_add_set(self._get_completed_source_ids_cache(), source_node_id)
if source_node_id not in self.executed_history:
self._tx_append_list(self.executed_history, source_node_id)
@@ -575,7 +639,7 @@ class GraphExecutionState(BaseModel):
if exec_node_id in self.executed:
return
self._tx_add_set(self.executed, exec_node_id)
- counts = self._unexecuted_prepared_counts
+ counts = self.__pydantic_private__["_runtime_state"].unexecuted_prepared_counts
if counts is None:
return
source_node_id = self.prepared_source_mapping.get(exec_node_id)
@@ -605,16 +669,18 @@ class GraphExecutionState(BaseModel):
def _count_unexecuted_prepared(self, source_node_id: str) -> int:
"""Return prepared exec nodes not yet executed or skipped for source."""
- if self._unexecuted_prepared_counts is None:
- self._unexecuted_prepared_counts = {
+ runtime = self.__pydantic_private__["_runtime_state"]
+ if runtime.unexecuted_prepared_counts is None:
+ runtime.unexecuted_prepared_counts = {
mapped_source_id: sum(1 for exec_node_id in prepared_ids if exec_node_id not in self.executed)
for mapped_source_id, prepared_ids in self.source_prepared_mapping.items()
}
- return self._unexecuted_prepared_counts.get(source_node_id, 0)
+ return runtime.unexecuted_prepared_counts.get(source_node_id, 0)
def _get_completed_source_ids_cache(self) -> set[str]:
- if self._completed_source_ids_cache is None:
- self._completed_source_ids_cache = {
+ runtime = self.__pydantic_private__["_runtime_state"]
+ if runtime.completed_source_ids_cache is None:
+ runtime.completed_source_ids_cache = {
source_node_id
for source_node_id in self.graph.nodes
if source_node_id in self.executed
@@ -624,7 +690,7 @@ class GraphExecutionState(BaseModel):
)
or self._is_source_inactive(source_node_id)
}
- return self._completed_source_ids_cache
+ return runtime.completed_source_ids_cache
def _get_for_source_by_return_id(self) -> dict[str, str]:
if self._for_source_by_return_id is None:
@@ -639,22 +705,25 @@ class GraphExecutionState(BaseModel):
return self._for_source_by_return_id
def _invalidate_source_graph_cache(self) -> None:
- self._source_graph_flat = None
- self._for_source_by_return_id = None
- self._if_branch_sources_cache = {}
- self._if_activation_dependencies_by_source = {}
- self._if_activation_dependencies_by_exec = {}
- self._if_activation_controller_instance = None
+ runtime = self.__pydantic_private__["_runtime_state"]
+ runtime.source_graph_flat = None
+ runtime.for_source_by_return_id = None
+ runtime.if_branch_sources_cache = {}
+ runtime.if_activation_dependencies_by_source = {}
+ runtime.if_activation_dependencies_by_exec = {}
+ runtime.if_activation_controller_instance = None
def _materializer(self) -> _ExecutionMaterializer:
- if self._execution_materializer is None:
- self._execution_materializer = _ExecutionMaterializer(self)
- return self._execution_materializer
+ runtime = self.__pydantic_private__["_runtime_state"]
+ if runtime.execution_materializer is None:
+ runtime.execution_materializer = _ExecutionMaterializer(self)
+ return runtime.execution_materializer
def _for_planner(self) -> _GenericForPlanner:
- if self._generic_for_planner is None:
- self._generic_for_planner = _GenericForPlanner(self)
- return self._generic_for_planner
+ runtime = self.__pydantic_private__["_runtime_state"]
+ if runtime.generic_for_planner is None:
+ runtime.generic_for_planner = _GenericForPlanner(self)
+ return runtime.generic_for_planner
def _create_for_body_iteration(self, source_for_id: str, prepared_for_id: str) -> Optional[str]:
if self._is_generic_graph_scheduler(self._scheduler()) and self._can_use_generic_for_scheduler():
@@ -756,7 +825,7 @@ class GraphExecutionState(BaseModel):
if existing is None:
self._tx_set_mapping(self.execution_tokens, token_id, token)
else:
- self._tx_set_attr(existing, "value", copydeep(token.value))
+ self._tx_set_attr(existing, "value", token.value)
def _apply_for_continuation(
self,
@@ -1329,13 +1398,14 @@ class GraphExecutionState(BaseModel):
return not any(isinstance(node, CallSavedWorkflowInvocation) for node in self.graph.nodes.values())
def _scheduler(self) -> _ExecutionScheduler | _GenericGraphSchedulerAdapter:
- if self._execution_scheduler is None:
+ runtime = self.__pydantic_private__["_runtime_state"]
+ if runtime.execution_scheduler is None:
if self._can_use_generic_scheduler():
- self._generic_graph_scheduler = _GenericGraphSchedulerAdapter(self)
- self._execution_scheduler = self._generic_graph_scheduler
+ runtime.generic_graph_scheduler = _GenericGraphSchedulerAdapter(self)
+ runtime.execution_scheduler = runtime.generic_graph_scheduler
else:
- self._execution_scheduler = _ExecutionScheduler(self)
- return self._execution_scheduler
+ runtime.execution_scheduler = _ExecutionScheduler(self)
+ return runtime.execution_scheduler
def _is_generic_graph_scheduler(self, scheduler: Any) -> bool:
return isinstance(scheduler, _GenericGraphSchedulerAdapter)
@@ -1344,16 +1414,18 @@ class GraphExecutionState(BaseModel):
return uuid_string()
def _runtime(self) -> _ExecutionRuntime:
- if self._execution_runtime is None:
- self._execution_runtime = _ExecutionRuntime(self)
- return self._execution_runtime
+ runtime = self.__pydantic_private__["_runtime_state"]
+ if runtime.execution_runtime is None:
+ runtime.execution_runtime = _ExecutionRuntime(self)
+ return runtime.execution_runtime
def _generic_runtime(self) -> ExecutionEngineRuntime:
"""Return the private typed runtime used by legacy-control adapters."""
- if self._generic_execution_runtime is None:
- self._generic_execution_runtime = ExecutionEngineRuntime()
- return self._generic_execution_runtime
+ runtime_state = self.__pydantic_private__["_runtime_state"]
+ if runtime_state.generic_execution_runtime is None:
+ runtime_state.generic_execution_runtime = ExecutionEngineRuntime()
+ return runtime_state.generic_execution_runtime
def _clear_transient_runtime(self) -> None:
"""Clear scheduling projections after execution reaches a terminal error."""
@@ -1398,7 +1470,12 @@ class GraphExecutionState(BaseModel):
return f"{self.id}:iterate:{source_node_id}:{path}"
def _record_iterate_stream(
- self, exec_node_id: str, output: BaseInvocationOutput, *, prefer_existing: bool = False
+ self,
+ exec_node_id: str,
+ output: BaseInvocationOutput,
+ *,
+ prefer_existing: bool = False,
+ trusted: bool = False,
) -> None:
if not isinstance(output, IterateInvocationOutput):
return
@@ -1433,7 +1510,12 @@ class GraphExecutionState(BaseModel):
else:
raise ValueError(f"Iterate result conflicts with closed stream {stream_id}")
if not skip_data:
- stream.accept(StreamData(sequence=output.index, value=copydeep(output.item)))
+ event = (
+ StreamData.model_construct(kind="data", sequence=output.index, value=output.item)
+ if trusted
+ else StreamData(sequence=output.index, value=output.item)
+ )
+ stream.accept(event, trusted=trusted)
if output.index + 1 >= output.total:
if stream.closed:
if stream.end_sequence != output.total:
@@ -1460,7 +1542,9 @@ class GraphExecutionState(BaseModel):
)
stream.close(sequence=stream.next_sequence)
- def _record_effect_streams(self, execution_ref: ExecutionReference, effects: Iterable[Any]) -> None:
+ def _record_effect_streams(
+ self, execution_ref: ExecutionReference, effects: Iterable[Any], *, trusted: bool = False
+ ) -> None:
"""Mirror generic stream effects into the private stream registry."""
for effect in effects:
@@ -1518,7 +1602,12 @@ class GraphExecutionState(BaseModel):
value = self._value_from_object(effect, "value")
if value is None:
value = self._value_from_object(token, "value")
- stream.accept(StreamData(sequence=sequence, value=copydeep(value)))
+ event = (
+ StreamData.model_construct(kind="data", sequence=sequence, value=value)
+ if trusted
+ else StreamData(sequence=sequence, value=value)
+ )
+ stream.accept(event, trusted=trusted)
def _stream_for_iterate_edge(self, edge: Edge) -> tuple[str, tuple[Any, ...]] | None:
source_node_id = self.prepared_source_mapping.get(edge.source.node_id)
@@ -2264,6 +2353,7 @@ class GraphExecutionState(BaseModel):
effect_count: Optional[int],
*,
require_continuation: bool = False,
+ validate_json: bool = True,
) -> list[Any]:
expected_count = effect_count if effect_count is not None else execution_ref.effect_count
if expected_count is not None and len(effects) != expected_count:
@@ -2278,10 +2368,11 @@ class GraphExecutionState(BaseModel):
awaited_child_ids: list[str] = []
lifecycle_effect_kinds: set[str] = set()
for effect in effects:
- try:
- _JSON_SERIALIZER.dump_python(effect, mode="json", warnings="error")
- except (PydanticSerializationError, TypeError, ValueError) as exc:
- raise ValueError("Execution effect must be JSON-serializable") from exc
+ if validate_json:
+ try:
+ _JSON_SERIALIZER.dump_python(effect, mode="json", warnings="error")
+ except (PydanticSerializationError, TypeError, ValueError) as exc:
+ raise ValueError("Execution effect must be JSON-serializable") from exc
effect_kind = self._value_from_object(effect, "kind", "effect_type", "type")
if effect_kind in {"spawn_execution", "await", "fail"}:
lifecycle_effect_kinds.add(effect_kind)
@@ -2579,7 +2670,7 @@ class GraphExecutionState(BaseModel):
owner_node_id=execution_ref.exec_node_id,
port=port,
frame=execution_ref.frame,
- value=copydeep(getattr(output, port)),
+ value=getattr(output, port),
)
for effect in effects:
effect_kind = self._value_from_object(effect, "kind", "effect_type", "type")
@@ -2622,7 +2713,7 @@ class GraphExecutionState(BaseModel):
owner_node_id=execution_ref.exec_node_id,
port=port,
frame=execution_ref.frame,
- value=copydeep(token_value),
+ value=token_value,
token_kind="stream_end" if effect_kind == "close_stream" else token_kind,
sequence=sequence,
)
@@ -3239,11 +3330,46 @@ class GraphExecutionState(BaseModel):
def _rehydrate_generic_runtime_state(self) -> None:
"""Rebuild private stream/continuation adapters from durable results."""
+ iterate_stream_needed_cache: dict[str, bool] = {}
+
+ def iterate_stream_needed(source_node_id: str) -> bool:
+ """Keep an Iterate stream only while a prepared item or Collect consumer can still need it."""
+
+ if source_node_id in iterate_stream_needed_cache:
+ return iterate_stream_needed_cache[source_node_id]
+ # Raw model snapshots predate the compact runtime projection and retain the legacy stream behavior.
+ if self._legacy_execution_snapshot and not self._execution_effects_persisted:
+ iterate_stream_needed_cache[source_node_id] = True
+ return True
+ if any(
+ isinstance(self.graph.nodes.get(edge.destination.node_id), CollectInvocation)
+ and edge.destination.node_id not in self.executed
+ for edge in self.graph._get_output_edges(source_node_id, ITEM_FIELD)
+ ):
+ iterate_stream_needed_cache[source_node_id] = True
+ return True
+ prepared_ids = self.source_prepared_mapping.get(source_node_id, ())
+ if any(exec_node_id not in self.executed for exec_node_id in prepared_ids):
+ iterate_stream_needed_cache[source_node_id] = True
+ return True
+ if not prepared_ids:
+ iterate_stream_needed_cache[source_node_id] = False
+ return False
+ needed = any(
+ isinstance(self.execution_graph.nodes.get(edge.destination.node_id), CollectInvocation)
+ and edge.destination.node_id not in self.executed
+ for exec_node_id in prepared_ids
+ for edge in self.execution_graph._get_output_edges(exec_node_id, ITEM_FIELD)
+ )
+ iterate_stream_needed_cache[source_node_id] = needed
+ return needed
+
for source_node_id, source_node in self.graph.nodes.items():
if (
isinstance(source_node, IterateInvocation)
and source_node_id in self.executed
and not self.source_prepared_mapping.get(source_node_id)
+ and iterate_stream_needed(source_node_id)
):
self._record_empty_iterate_stream(source_node_id)
@@ -3272,9 +3398,10 @@ class GraphExecutionState(BaseModel):
list(effects),
len(effects),
require_continuation=self._requires_continuation_effect(execution_ref),
+ validate_json=not self._execution_effects_persisted,
)
self._record_continuation_effects(execution_ref, effects)
- self._record_effect_streams(execution_ref, effects)
+ self._record_effect_streams(execution_ref, effects, trusted=self._execution_effects_persisted)
elif self._legacy_execution_snapshot:
for reference_id, effects in self.execution_effects.items():
execution_ref = next(
@@ -3295,7 +3422,13 @@ class GraphExecutionState(BaseModel):
if execution_ref.reference_id not in self.execution_effects:
raise ValueError(f"{type(node).__name__} execution must include a continuation effect")
effects = self.execution_effects[execution_ref.reference_id]
- self._validate_effects(execution_ref, list(effects), len(effects), require_continuation=True)
+ self._validate_effects(
+ execution_ref,
+ list(effects),
+ len(effects),
+ require_continuation=True,
+ validate_json=not self._execution_effects_persisted,
+ )
if self._execution_effects_persisted:
self._validate_for_continuation_output(execution_ref, output)
@@ -3305,7 +3438,10 @@ class GraphExecutionState(BaseModel):
iterate_results.append((exec_node_id, output))
iterate_results.sort(key=lambda item: (self._get_iteration_path(item[0]), item[1].index, item[0]))
for exec_node_id, output in iterate_results:
- self._record_iterate_stream(exec_node_id, output, prefer_existing=True)
+ source_node_id = self.prepared_source_mapping.get(exec_node_id)
+ if source_node_id is None or not iterate_stream_needed(source_node_id):
+ continue
+ self._record_iterate_stream(exec_node_id, output, prefer_existing=True, trusted=True)
for exec_node_id, node in self.execution_graph.nodes.items():
if isinstance(node, ForInvocation) and node.index >= 0 and exec_node_id in self.results:
@@ -3741,3 +3877,59 @@ class GraphExecutionState(BaseModel):
)
self.graph.delete_edge(edge)
self._invalidate_source_graph_cache()
+
+
+_GRAPH_RUNTIME_ATTRIBUTE_NAMES = (
+ "ready_queues",
+ "ready_node_ids",
+ "active_class",
+ "resolved_if_exec_branches",
+ "pending_if_exec_nodes",
+ "if_branch_sources_cache",
+ "if_activation_dependencies_by_source",
+ "if_activation_dependencies_by_exec",
+ "prepared_if_exec_ids_by_source_and_frame",
+ "prepared_if_exec_frames_by_source",
+ "prepared_if_exec_indexed_sources",
+ "prepared_exec_metadata",
+ "prepared_exec_registry",
+ "if_activation_controller_instance",
+ "execution_materializer",
+ "generic_for_planner",
+ "execution_scheduler",
+ "execution_runtime",
+ "for_parent_iteration_paths_cache",
+ "all_for_contexts_finalized_cache",
+ "prepared_for_index",
+ "final_prepared_for_index",
+ "prepared_for_index_by_exec",
+ "source_graph_flat",
+ "execution_graph_flat",
+ "completed_source_ids_cache",
+ "unexecuted_prepared_counts",
+ "for_source_by_return_id",
+ "apply_transaction",
+ "generic_execution_runtime",
+ "generic_graph_scheduler",
+ "generic_child_dependencies",
+ "pending_lifecycle_execution_nodes",
+ "execution_effects_persisted",
+ "legacy_execution_snapshot",
+ "legacy_snapshot_loaded",
+)
+
+
+def _runtime_state_property(name: str) -> property:
+ def getter(state: GraphExecutionState) -> Any:
+ # Access the single PrivateAttr through pydantic's storage directly. Using ``state._runtime_state``
+ # here would put every compatibility-property access back through BaseModel.__getattr__.
+ return getattr(state.__pydantic_private__["_runtime_state"], name)
+
+ def setter(state: GraphExecutionState, value: Any) -> None:
+ setattr(state.__pydantic_private__["_runtime_state"], name, value)
+
+ return property(getter, setter)
+
+
+for _runtime_attribute_name in _GRAPH_RUNTIME_ATTRIBUTE_NAMES:
+ setattr(GraphExecutionState, f"_{_runtime_attribute_name}", _runtime_state_property(_runtime_attribute_name))
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index d657518c87..70b60d622f 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -108,6 +108,7 @@ class _ExecutionScheduler:
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
+ self._runtime_state = state.__pydantic_private__["_runtime_state"]
def _validate_exec_node_ready_state(self, exec_node_id: str) -> None:
if exec_node_id not in self._state.execution_graph.nodes:
@@ -218,19 +219,21 @@ class _ExecutionScheduler:
self.enqueue_if_ready(child)
def queue_for(self, cls_name: str) -> Deque[str]:
- q = self._state._ready_queues.get(cls_name)
+ runtime = self._runtime_state
+ q = runtime.ready_queues.get(cls_name)
if q is None:
q = deque()
- self._state._tx_set_mapping(self._state._ready_queues, cls_name, q)
+ self._state._tx_set_mapping(runtime.ready_queues, cls_name, q)
return q
def remove_from_ready_queues(self, exec_node_id: str) -> None:
- for q in self._state._ready_queues.values():
+ runtime = self._runtime_state
+ for q in runtime.ready_queues.values():
try:
self._state._tx_queue_remove(q, exec_node_id)
except ValueError:
continue
- self._state._tx_discard_set(self._state._ready_node_ids, exec_node_id)
+ self._state._tx_discard_set(runtime.ready_node_ids, exec_node_id)
def mark_skipped(self, exec_node_id: str) -> None:
"""Satisfy downstream indegrees without resolving inputs from a skipped node."""
@@ -249,50 +252,52 @@ 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 self._state._ready_node_ids:
+ runtime = self._runtime_state
+ if exec_node_id in runtime.ready_node_ids:
return
self._state._set_prepared_exec_state(exec_node_id, "ready")
self._insert_ready_node(queue, exec_node_id)
- self._state._tx_add_set(self._state._ready_node_ids, exec_node_id)
+ self._state._tx_add_set(runtime.ready_node_ids, exec_node_id)
def get_next_node(self) -> Optional[BaseInvocation]:
"""Gets the next ready node: FIFO within class, drain class before switching."""
+ runtime = self._runtime_state
while True:
- if not self._state._active_class and self._state.results:
+ if not runtime.active_class and self._state.results:
last_exec_node_id = next(reversed(self._state.results))
last_node = self._state.execution_graph.nodes.get(last_exec_node_id)
if last_node is not None:
last_class = self._state._type_key(last_node)
- if self._state._ready_queues.get(last_class):
- self._state._active_class = last_class
- if self._state._active_class:
- q = self._state._ready_queues.get(self._state._active_class)
+ if runtime.ready_queues.get(last_class):
+ runtime.active_class = last_class
+ if runtime.active_class:
+ q = runtime.ready_queues.get(runtime.active_class)
while q:
exec_node_id = q.popleft()
- self._state._ready_node_ids.discard(exec_node_id)
+ runtime.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
+ runtime.active_class = None
continue
seen = set(self._state.ready_order)
next_class = next(
- (cls_name for cls_name in self._state.ready_order if self._state._ready_queues.get(cls_name)),
+ (cls_name for cls_name in self._state.ready_order if runtime.ready_queues.get(cls_name)),
None,
)
if next_class is None:
next_class = next(
(
cls_name
- for cls_name in sorted(k for k in self._state._ready_queues.keys() if k not in seen)
- if self._state._ready_queues[cls_name]
+ for cls_name in sorted(k for k in runtime.ready_queues.keys() if k not in seen)
+ if runtime.ready_queues[cls_name]
),
None,
)
if next_class is None:
return None
- self._state._active_class = next_class
+ runtime.active_class = next_class
def complete(
self, exec_node_id: str, output: BaseInvocationOutput
@@ -346,6 +351,7 @@ class _GenericGraphSchedulerAdapter:
def __init__(self, state: "GraphExecutionState") -> None:
self._state = state
+ self._runtime_state = state.__pydantic_private__["_runtime_state"]
self._initializing = True
self._if_exec_ids: dict[str, None] = {}
self._scheduler = ExecutionScheduler(
@@ -412,7 +418,8 @@ class _GenericGraphSchedulerAdapter:
def resolve_if_node(self, exec_node_id: str, *, enqueue: bool = True) -> None:
"""Resolve legacy If inputs without pruning graph edges or using type-specific skips."""
- if exec_node_id in self._state._resolved_if_exec_branches:
+ runtime = self._runtime_state
+ if exec_node_id in runtime.resolved_if_exec_branches:
return
node = self._state.execution_graph.get_node(exec_node_id)
if not isinstance(node, IfInvocation):
@@ -422,7 +429,7 @@ class _GenericGraphSchedulerAdapter:
selected_field = "true_input" if node.condition else "false_input"
self._state._resolve_activation_gate(exec_node_id, selected_field)
- self._state._tx_set_mapping(self._state._resolved_if_exec_branches, exec_node_id, selected_field)
+ self._state._tx_set_mapping(runtime.resolved_if_exec_branches, exec_node_id, selected_field)
self._state._record_compatibility_activation_token(exec_node_id, selected_field)
self._discard_rejected_nodes()
self._sync_indegree()
@@ -503,14 +510,15 @@ class _GenericGraphSchedulerAdapter:
self._state._tx_set_mapping(self._state.indegree, exec_node_id, degree)
def _project_ready_node(self, exec_node_id: str) -> None:
- if not self._scheduler.is_ready(exec_node_id) or exec_node_id in self._state._ready_node_ids:
+ runtime = self._runtime_state
+ if not self._scheduler.is_ready(exec_node_id) or exec_node_id in runtime.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)
+ queue = runtime.ready_queues.get(cls_name)
if queue is None:
queue = deque()
- self._state._tx_set_mapping(self._state._ready_queues, cls_name, queue)
+ self._state._tx_set_mapping(runtime.ready_queues, cls_name, queue)
iteration_path = self._state._get_iteration_path(exec_node_id)
if not queue or self._state._get_iteration_path(queue[-1]) <= iteration_path:
self._state._tx_queue_append(queue, exec_node_id)
@@ -522,7 +530,7 @@ class _GenericGraphSchedulerAdapter:
)
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)
+ self._state._tx_add_set(runtime.ready_node_ids, exec_node_id)
def _project_ready_nodes(self) -> None:
for exec_node_id in self._scheduler.ready_ids:
@@ -540,18 +548,20 @@ class _GenericGraphSchedulerAdapter:
self.enqueue_if_ready(exec_node_id)
def _remove_projected(self, exec_node_id: str) -> None:
- for queue in self._state._ready_queues.values():
+ runtime = self._runtime_state
+ for queue in runtime.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)
+ self._state._tx_discard_set(runtime.ready_node_ids, exec_node_id)
def queue_for(self, cls_name: str) -> Deque[str]:
- queue = self._state._ready_queues.get(cls_name)
+ runtime = self._runtime_state
+ queue = runtime.ready_queues.get(cls_name)
if queue is None:
queue = deque()
- self._state._tx_set_mapping(self._state._ready_queues, cls_name, queue)
+ self._state._tx_set_mapping(runtime.ready_queues, cls_name, queue)
return queue
def remove_from_ready_queues(self, exec_node_id: str) -> None:
diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.py
index 45dcec3a6f..650536abb1 100644
--- a/invokeai/app/services/shared/graph_validation.py
+++ b/invokeai/app/services/shared/graph_validation.py
@@ -614,6 +614,16 @@ class _EdgeList(list[Edge]):
super().sort(key=key, reverse=reverse)
+class _GraphEdgeIndexes:
+ """Process-local adjacency indexes kept out of pydantic's attribute lookup path."""
+
+ __slots__ = ("input_edges_by_node", "output_edges_by_node")
+
+ def __init__(self) -> None:
+ self.input_edges_by_node: Optional[dict[str, list[Edge]]] = None
+ self.output_edges_by_node: Optional[dict[str, list[Edge]]] = None
+
+
class Graph(BaseModel):
"""A validated invocation graph made of nodes and typed edges."""
@@ -624,8 +634,7 @@ 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)
+ _edge_indexes: _GraphEdgeIndexes = PrivateAttr(default_factory=_GraphEdgeIndexes)
def _rebind_edge_list(self) -> None:
object.__setattr__(self, "edges", _EdgeList(self.edges, self))
@@ -636,16 +645,19 @@ class Graph(BaseModel):
def model_copy(self, *, update: Optional[dict[str, Any]] = None, deep: bool = False) -> "Graph":
copied = super().model_copy(update=update, deep=deep)
+ copied.__pydantic_private__["_edge_indexes"] = _GraphEdgeIndexes()
copied._rebind_edge_list()
return copied
def __copy__(self) -> "Graph":
copied = super().__copy__()
+ copied.__pydantic_private__["_edge_indexes"] = _GraphEdgeIndexes()
copied._rebind_edge_list()
return copied
def __deepcopy__(self, memo: Optional[dict[int, Any]] = None) -> "Graph":
copied = super().__deepcopy__(memo)
+ copied.__pydantic_private__["_edge_indexes"] = _GraphEdgeIndexes()
copied._rebind_edge_list()
return copied
@@ -667,11 +679,13 @@ class Graph(BaseModel):
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
+ indexes = self.__pydantic_private__["_edge_indexes"]
+ indexes.input_edges_by_node = None
+ indexes.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:
+ indexes = self.__pydantic_private__["_edge_indexes"]
+ if indexes.input_edges_by_node is not None and indexes.output_edges_by_node is not None:
return
input_edges_by_node: dict[str, list[Edge]] = {}
@@ -679,22 +693,24 @@ class Graph(BaseModel):
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
+ indexes.input_edges_by_node = input_edges_by_node
+ indexes.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)
+ indexes = self.__pydantic_private__["_edge_indexes"]
+ if indexes.input_edges_by_node is not None:
+ indexes.input_edges_by_node.setdefault(edge.destination.node_id, []).append(edge)
+ if indexes.output_edges_by_node is not None:
+ indexes.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)
+ indexes = self.__pydantic_private__["_edge_indexes"]
+ if indexes.input_edges_by_node is not None:
+ input_edges = indexes.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 indexes.output_edges_by_node is not None:
+ output_edges = indexes.output_edges_by_node.get(edge.source.node_id)
if output_edges is not None:
output_edges.remove(edge)
@@ -1100,8 +1116,9 @@ class Graph(BaseModel):
"""Gets all input edges for a node. If field is provided, only edges to that field are returned."""
self._ensure_edge_indexes()
- assert self._input_edges_by_node is not None
- edges = self._input_edges_by_node.get(node_id, [])
+ indexes = self.__pydantic_private__["_edge_indexes"]
+ assert indexes.input_edges_by_node is not None
+ edges = indexes.input_edges_by_node.get(node_id, [])
if not include_loop_linkage:
edges = [edge for edge in edges if edge.type == "default"]
@@ -1117,8 +1134,9 @@ class Graph(BaseModel):
) -> list[Edge]:
"""Gets all output edges for a node. If field is provided, only edges from that field are returned."""
self._ensure_edge_indexes()
- assert self._output_edges_by_node is not None
- edges = self._output_edges_by_node.get(node_id, [])
+ indexes = self.__pydantic_private__["_edge_indexes"]
+ assert indexes.output_edges_by_node is not None
+ edges = indexes.output_edges_by_node.get(node_id, [])
if not include_loop_linkage:
edges = [edge for edge in edges if edge.type == "default"]
@@ -2080,3 +2098,17 @@ class Graph(BaseModel):
edges = dict.fromkeys((e.source.node_id, e.destination.node_id) for e in self.edges if e.type == "default")
g.add_edges_from(edges)
return g
+
+
+def _edge_index_property(name: str) -> property:
+ def getter(graph: Graph) -> Optional[dict[str, list[Edge]]]:
+ return getattr(graph.__pydantic_private__["_edge_indexes"], name)
+
+ def setter(graph: Graph, value: Optional[dict[str, list[Edge]]]) -> None:
+ setattr(graph.__pydantic_private__["_edge_indexes"], name, value)
+
+ return property(getter, setter)
+
+
+Graph._input_edges_by_node = _edge_index_property("input_edges_by_node")
+Graph._output_edges_by_node = _edge_index_property("output_edges_by_node")
diff --git a/tests/app/services/shared/test_execution_engine_primitives.py b/tests/app/services/shared/test_execution_engine_primitives.py
index 223278f2c2..cc4278530a 100644
--- a/tests/app/services/shared/test_execution_engine_primitives.py
+++ b/tests/app/services/shared/test_execution_engine_primitives.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Any
+
import pytest
from pydantic import ValidationError
@@ -93,6 +95,12 @@ def test_stream_buffer_preserves_order_and_none_values() -> None:
assert isinstance(buffer.events[-1], StreamEnd)
[email protected]("value", [[], {}, {"nested": []}, None])
+def test_stream_data_keeps_json_values_by_reference(value: Any) -> None:
+ event = StreamData(sequence=0, value=value)
+ assert event.value is value
+
+
def test_stream_buffer_rejects_conflicting_duplicate_and_out_of_order_events() -> None:
buffer = StreamBuffer[int](stream_id="stream", owner_id="iterate", frame=_frame())
buffer.accept(StreamData(sequence=0, value=1))
@@ -128,6 +136,18 @@ def test_stream_buffer_validates_event_json_and_round_trips() -> None:
StreamData(sequence=0, value=object())
+def test_stream_buffer_trusted_rehydration_skips_only_value_serialization() -> None:
+ value = object()
+ event = StreamData.model_construct(kind="data", sequence=0, value=value)
+ buffer = StreamBuffer[Any](stream_id="stream", owner_id="iterate", frame=_frame())
+
+ assert buffer.accept(event, trusted=True) is True
+ assert buffer.events[0].value is value
+
+ with pytest.raises(ValueError, match="JSON-serializable"):
+ StreamBuffer[Any](stream_id="other", owner_id="iterate", frame=_frame()).accept("data", value=value)
+
+
def test_continuation_record_has_atomic_idempotent_status_transitions() -> None:
continuation = ContinuationRecord[dict[str, int]](
continuation_id="continuation",
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index 4ed6cad019..22dc2ff11a 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -1,3 +1,4 @@
+import copy
from collections import defaultdict, deque
from collections.abc import Iterator
from types import SimpleNamespace
@@ -272,6 +273,23 @@ def test_graph_state_apply_stores_stable_frame_tokens_and_effects():
assert restored.execution_tokens == {}
+def test_graph_state_output_tokens_retain_mutable_result_values_by_reference():
+ graph = Graph()
+ graph.add_node(BooleanCollectionInvocation(id="values", collection=[True, False]))
+ state = GraphExecutionState(graph=graph)
+ node = state.next()
+ assert node is not None
+ output = node.invoke(Mock(InvocationContext))
+ ref = state.get_execution_ref(node.id)
+
+ state.apply(ref, output)
+
+ token = state.execution_tokens[f"{ref.reference_id}:collection"]
+ assert token.value is output.collection
+ output.collection.append(True)
+ assert token.value == [True, False, True]
+
+
def test_graph_state_apply_accepts_protocol_ref_without_token():
graph = Graph()
graph.add_node(AddInvocation(id="add", a=1, b=2))
@@ -804,6 +822,21 @@ def test_rehydrated_iterate_state_can_be_deep_copied_without_sharing_runtime_loc
assert closed_stream.values == (0, 1)
+ "copy_state",
+ [pytest.param(lambda state: state.model_copy(), id="model_copy"), pytest.param(copy.copy, id="copy")],
+)
+def test_graph_state_shallow_copy_reset_does_not_clear_original_runtime_state(copy_state):
+ state = GraphExecutionState(graph=Graph())
+ state._ready_queues["test"] = deque(["node"])
+
+ copied = copy_state(state)
+ copied._reset_runtime_caches()
+
+ assert state._ready_queues == {"test": deque(["node"])}
+ assert not copied._ready_queues
+
+
@pytest.mark.parametrize("port", ["type", "output_meta", "loop_linkage"])
@pytest.mark.parametrize("effect_kind, token_kind", [("emit", "data"), ("close_stream", "stream_end")])
def test_graph_state_apply_rejects_reserved_effect_ports(port: str, effect_kind: str, token_kind: str):