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.

feat(execution): wire effects through graph application

JPPhoto653b8c398675
diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.py
index 261d9efa5a..5cd7981788 100644
--- a/invokeai/app/invocations/baseinvocation.py
+++ b/invokeai/app/invocations/baseinvocation.py
@@ -264,11 +264,14 @@ class BaseInvocation(ABC, BaseModel):
) -> InvocationRunResult:
"""Invoke while returning effects recorded by the invocation context.
- This additive path intentionally bypasses the ordinary invocation cache.
- Cache entries contain outputs only, so using one here could suppress a
- newly recorded effect batch without notice. Existing ``invoke_internal``
- callers retain their current cache behavior.
+ Ordinary invocations retain the existing output-only cache. Invocations
+ that declare ``execution_effects_enabled`` bypass that cache because a
+ cache hit cannot safely replay activation, stream, child, or failure
+ effects.
"""
+ if not self.execution_effects_enabled:
+ return InvocationRunResult(output=self.invoke_internal(context, services), effects=())
+
self._validate_invoke_fields()
context.execution_effects.clear()
if self.use_cache and services.configuration.node_cache_size != 0:
@@ -296,6 +299,8 @@ class BaseInvocation(ABC, BaseModel):
bottleneck: ClassVar[Bottleneck]
+ execution_effects_enabled: ClassVar[bool] = False
+
idle_gpu_offloadable: ClassVar[bool] = False
"""Whether this node's entire execution may be temporarily re-pinned to an idle GPU when
`offload_text_encoders_to_idle_gpus` is enabled in multi-GPU mode. Only set this to True on nodes
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index d969836c1e..68b5f7da82 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -275,12 +275,14 @@ class DefaultSessionRunner(SessionRunnerBase):
# Invoke the node, optionally on a borrowed idle GPU (text encoders only).
with self._maybe_offload_to_idle_gpu(invocation):
- output = invocation.invoke_internal(context=context, services=self._services)
+ run_result = invocation.invoke_internal_with_effects(context=context, services=self._services)
+ output = run_result.output
control_collection = None
if self._on_after_run_node_callbacks and isinstance(invocation, (IterateInvocation, CollectInvocation)):
control_collection = invocation.collection
# Save output and history
- finalized_outputs = queue_item.session.complete(invocation.id, output)
+ execution_ref = queue_item.session.get_execution_ref(invocation.id, effect_count=len(run_result.effects))
+ finalized_outputs = queue_item.session.apply(execution_ref, run_result)
if control_collection is not None:
invocation.collection = control_collection
diff --git a/invokeai/app/services/session_queue/session_queue_common.py b/invokeai/app/services/session_queue/session_queue_common.py
index b9738c6c2e..fb6173b8a1 100644
--- a/invokeai/app/services/session_queue/session_queue_common.py
+++ b/invokeai/app/services/session_queue/session_queue_common.py
@@ -16,6 +16,10 @@ from pydantic import (
from pydantic_core import to_jsonable_python
from invokeai.app.invocations.fields import ImageField, VideoField
+from invokeai.app.services.shared.execution_state_migration import (
+ CURRENT_EXECUTION_STATE_VERSION,
+ load_execution_state,
+)
from invokeai.app.services.shared.graph import Graph, GraphExecutionState, NodeNotFoundError
from invokeai.app.services.workflow_records.workflow_records_common import (
WorkflowWithoutID,
@@ -218,13 +222,10 @@ def get_field_values(queue_item_dict: dict) -> Optional[list[NodeFieldValue]]:
return NodeFieldValueValidator.validate_json(field_values_raw) if field_values_raw is not None else None
-GraphExecutionStateValidator = TypeAdapter(GraphExecutionState)
-
-
def get_session(queue_item_dict: dict) -> GraphExecutionState:
session_raw = queue_item_dict.get("session", "{}")
- session = GraphExecutionStateValidator.validate_json(session_raw, strict=False)
- return session
+ session_payload = json.loads(session_raw) if isinstance(session_raw, str) else session_raw
+ return load_execution_state(session_payload)
def get_workflow(queue_item_dict: dict) -> Optional[WorkflowWithoutID]:
@@ -610,6 +611,7 @@ def create_session_nfv_tuples(batch: Batch, maximum: int) -> Generator[tuple[str
# We must provide a Graph object when creating the "dummy" session dict, but we don't actually use it. It will be
# overwritten for each session by the mutated graph_as_dict.
session_dict = GraphExecutionState(graph=Graph()).model_dump(warnings=False, exclude_none=True)
+ session_dict["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSION
# Now we can create a generator that yields the session_id, session_json, and field_values_json for each session.
count = 0
diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.py
index ba5cef8569..451cbff533 100644
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@ -44,6 +44,7 @@ from invokeai.app.services.session_queue.session_queue_common import (
prepare_values_to_insert,
uuid_string,
)
+from invokeai.app.services.shared.execution_state_migration import dump_execution_state
from invokeai.app.services.shared.graph import GraphExecutionState
from invokeai.app.services.shared.pagination import CursorPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
@@ -1407,7 +1408,7 @@ class SqliteSessionQueue(SessionQueueBase):
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. Persisted sessions are used to resume execution across queue boundaries.
- session_json = session.model_dump_json(warnings=False, exclude_none=True)
+ session_json = json.dumps(dump_execution_state(session), default=to_jsonable_python)
cursor.execute(
"""--sql
UPDATE session_queue
@@ -1433,7 +1434,7 @@ class SqliteSessionQueue(SessionQueueBase):
if workflow_call_execution is None:
raise ValueError("Parent queue item is missing active workflow call execution metadata.")
- session_json = child_session.model_dump_json(warnings=False, exclude_none=True)
+ session_json = json.dumps(dump_execution_state(child_session), default=to_jsonable_python)
field_values_json = json.dumps(field_values, default=to_jsonable_python) if field_values is not None else None
root_item_id = parent_queue_item.root_item_id or parent_queue_item.item_id
@@ -1920,7 +1921,7 @@ class SqliteSessionQueue(SessionQueueBase):
else None
)
cloned_session = GraphExecutionState(graph=root_queue_item.session.graph)
- cloned_session_json = cloned_session.model_dump_json(warnings=False, exclude_none=True)
+ cloned_session_json = json.dumps(dump_execution_state(cloned_session), default=to_jsonable_python)
retried_from_item_id = (
root_queue_item.retried_from_item_id
diff --git a/invokeai/app/services/shared/execution_effects.py b/invokeai/app/services/shared/execution_effects.py
index 67a3d6065e..32f078d3d4 100644
--- a/invokeai/app/services/shared/execution_effects.py
+++ b/invokeai/app/services/shared/execution_effects.py
@@ -8,7 +8,7 @@ engine migration.
from __future__ import annotations
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Literal, Union
+from typing import TYPE_CHECKING, Any, Callable, Literal, Union
from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator, model_validator
@@ -44,7 +44,12 @@ class ExecutionToken(_ExecutionModel):
node_id: str = Field(min_length=1, description="The execution node id.")
field: str = Field(min_length=1, description="The output field name.")
- frame: tuple[int, ...] = Field(default=(), description="The enclosing loop iteration path.")
+ value: Any | None = Field(default=None, description="The typed value carried by this token.")
+ frame: tuple[int | str, ...] = Field(default=(), description="The enclosing execution frame path.")
+ token_kind: Literal["data", "activation", "stream_end"] = Field(
+ default="data", description="The semantic kind of this token."
+ )
+ sequence: int | None = Field(default=None, ge=0, description="Stable order within a stream or frame.")
@model_validator(mode="before")
@classmethod
@@ -67,9 +72,11 @@ class ExecutionToken(_ExecutionModel):
@field_validator("frame")
@classmethod
- def _reject_negative_frame_parts(cls, value: tuple[int, ...]) -> tuple[int, ...]:
- if any(part < 0 for part in value):
+ def _reject_invalid_frame_parts(cls, value: tuple[int | str, ...]) -> tuple[int | str, ...]:
+ if any(isinstance(part, int) and part < 0 for part in value):
raise ValueError("frame values must be non-negative")
+ if any(isinstance(part, str) and not part.strip() for part in value):
+ raise ValueError("frame values must not be blank")
return value
@property
@@ -85,14 +92,29 @@ class ExecutionToken(_ExecutionModel):
return self.field
@property
- def iteration_path(self) -> tuple[int, ...]:
+ def iteration_path(self) -> tuple[int | str, ...]:
+ return self.frame
+
+ @property
+ def source_node_id(self) -> str:
+ return self.node_id
+
+ @property
+ def source_field(self) -> str:
+ return self.field
+
+ @property
+ def frame_path(self) -> tuple[int | str, ...]:
return self.frame
class ExecutionRef(_ExecutionModel):
"""Frame-aware reference to an execution token."""
- token: ExecutionToken
+ token: ExecutionToken | None = None
+ template_node_id: str | None = Field(default=None, min_length=1)
+ execution_node_id: str | None = Field(default=None, min_length=1)
+ frame_path: tuple[int | str, ...] = ()
scope: Literal["iteration", "final"] = "final"
@model_validator(mode="before")
@@ -101,9 +123,7 @@ class ExecutionRef(_ExecutionModel):
if not isinstance(value, dict):
return value
data = dict(value)
- if "token" not in data and any(
- name in data for name in ("node_id", "invocation_id", "field", "port", "output", "output_name")
- ):
+ if "token" not in data and any(name in data for name in ("node_id", "invocation_id", "field", "port", "output", "output_name")):
token_fields = {
name: data.pop(name)
for name in (
@@ -120,19 +140,39 @@ class ExecutionRef(_ExecutionModel):
if name in data
}
data["token"] = token_fields
+ if "execution_node_id" not in data:
+ if "node_id" in data:
+ data["execution_node_id"] = data["node_id"]
+ elif isinstance(data.get("token"), dict):
+ token_data = data["token"]
+ data["execution_node_id"] = token_data.get("node_id", token_data.get("invocation_id"))
+ if "frame_path" not in data and isinstance(data.get("token"), dict):
+ token_data = data["token"]
+ data["frame_path"] = token_data.get("frame", token_data.get("iteration_path", ()))
+ for alias in ("node_id", "invocation_id", "field", "port", "output", "output_name", "frame", "iteration_path"):
+ data.pop(alias, None)
return data
+ @model_validator(mode="after")
+ def _require_execution_identity(self) -> "ExecutionRef":
+ if self.token is None and self.execution_node_id is None:
+ raise ValueError("execution reference requires a token or execution_node_id")
+ return self
+
@property
def node_id(self) -> str:
+ if self.execution_node_id is not None:
+ return self.execution_node_id
+ assert self.token is not None
return self.token.node_id
@property
def field(self) -> str:
- return self.token.field
+ return self.token.field if self.token is not None else ""
@property
- def frame(self) -> tuple[int, ...]:
- return self.token.frame
+ def frame(self) -> tuple[int | str, ...]:
+ return self.frame_path or (self.token.frame if self.token is not None else ())
@property
def invocation_id(self) -> str:
@@ -143,8 +183,8 @@ class ExecutionRef(_ExecutionModel):
return self.token.field
@property
- def iteration_path(self) -> tuple[int, ...]:
- return self.token.frame
+ def iteration_path(self) -> tuple[int | str, ...]:
+ return self.frame
class ExecutionEffect(_ExecutionModel):
@@ -181,10 +221,41 @@ class RemoveEdgeEffect(ExecutionEffect):
class EmitEffect(ExecutionEffect):
kind: Literal["emit"] = "emit"
token: ExecutionToken
- value: JsonValue | None = None
+ value: Any | None = None
+
+
+class CloseStreamEffect(ExecutionEffect):
+ kind: Literal["close_stream"] = "close_stream"
+ token: ExecutionToken
+
+class SpawnExecutionEffect(ExecutionEffect):
+ kind: Literal["spawn_execution"] = "spawn_execution"
+ parent: ExecutionRef
+ graph: Any
+ inputs: dict[str, Any] = Field(default_factory=dict)
-ExecutionEffectModel = Union[SetValueEffect, AddEdgeEffect, RemoveEdgeEffect, EmitEffect]
+
+class AwaitEffect(ExecutionEffect):
+ kind: Literal["await"] = "await"
+ dependency: ExecutionRef
+
+
+class FailEffect(ExecutionEffect):
+ kind: Literal["fail"] = "fail"
+ message: str = Field(min_length=1)
+
+
+ExecutionEffectModel = Union[
+ SetValueEffect,
+ AddEdgeEffect,
+ RemoveEdgeEffect,
+ EmitEffect,
+ CloseStreamEffect,
+ SpawnExecutionEffect,
+ AwaitEffect,
+ FailEffect,
+]
# Descriptive aliases keep call sites free to use execution-specific names.
SetExecutionValueEffect = SetValueEffect
@@ -193,6 +264,73 @@ RemoveExecutionEdgeEffect = RemoveEdgeEffect
EmitExecutionEffect = EmitEffect
+class ExecutionInterface:
+ """Restricted recorder facade exposed to invocation code."""
+
+ def __init__(
+ self,
+ recorder: "ExecutionEffectsRecorder",
+ authorize_workflow: Callable[[str], Any] | None = None,
+ ) -> None:
+ self._recorder = recorder
+ self._authorize_workflow = authorize_workflow
+
+ def emit(
+ self,
+ field: str,
+ value: Any,
+ *,
+ frame: tuple[int | str, ...] | None = None,
+ sequence: int | None = None,
+ token_kind: Literal["data", "activation"] = "data",
+ ) -> None:
+ self._recorder.record(
+ EmitEffect(
+ token=ExecutionToken(
+ node_id=self._recorder.source_node_id,
+ field=field,
+ value=value,
+ frame=frame or self._recorder.frame_path,
+ token_kind=token_kind,
+ sequence=sequence,
+ ),
+ value=value,
+ )
+ )
+
+ def close_stream(self, field: str, *, frame: tuple[int | str, ...] | None = None) -> None:
+ self._recorder.record(
+ CloseStreamEffect(
+ token=ExecutionToken(
+ node_id=self._recorder.source_node_id,
+ field=field,
+ frame=frame or self._recorder.frame_path,
+ token_kind="stream_end",
+ )
+ )
+ )
+
+ def spawn(self, graph: Any, inputs: dict[str, Any]) -> None:
+ self._recorder.record(
+ SpawnExecutionEffect(
+ parent=ExecutionRef(execution_node_id=self._recorder.source_node_id, frame_path=self._recorder.frame_path),
+ graph=graph,
+ inputs=inputs,
+ )
+ )
+
+ def await_dependency(self, dependency: ExecutionRef) -> None:
+ self._recorder.record(AwaitEffect(dependency=dependency))
+
+ def fail(self, message: str) -> None:
+ self._recorder.record(FailEffect(message=message))
+
+ def authorize_workflow(self, workflow_id: str) -> Any:
+ if self._authorize_workflow is None:
+ raise PermissionError("workflow authorization is unavailable in this execution context")
+ return self._authorize_workflow(workflow_id)
+
+
@dataclass(frozen=True)
class ExecutionEffectBatch:
effects: tuple[ExecutionEffect, ...]
@@ -210,8 +348,10 @@ class ExecutionEffectBatch:
class ExecutionEffectsRecorder:
"""Collects effects for one invocation run."""
- def __init__(self) -> None:
+ def __init__(self, source_node_id: str = "context", frame_path: tuple[int | str, ...] = ()) -> None:
self._effects: list[ExecutionEffect] = []
+ self.source_node_id = source_node_id
+ self.frame_path = frame_path
def record(self, effect: ExecutionEffect) -> None:
if not isinstance(effect, ExecutionEffect):
diff --git a/invokeai/app/services/shared/execution_state_migration.py b/invokeai/app/services/shared/execution_state_migration.py
index 077bf34e41..1cce42640d 100644
--- a/invokeai/app/services/shared/execution_state_migration.py
+++ b/invokeai/app/services/shared/execution_state_migration.py
@@ -13,11 +13,16 @@ class UnsupportedExecutionStateVersionError(ValueError):
def dump_execution_state(state: GraphExecutionState) -> dict[str, Any]:
- """Dump an internal execution state in its versioned snapshot envelope."""
- return {
- "version": CURRENT_EXECUTION_STATE_VERSION,
- "state": state.model_dump(mode="json", warnings=False, exclude_none=True),
- }
+ """Dump an internal execution state with an additive version marker.
+
+ The marker stays alongside the existing state fields so rolling deployments
+ and diagnostic tools that still deserialize the legacy raw shape continue
+ to work. The loader also accepts the temporary envelope form used by early
+ migration experiments.
+ """
+ snapshot = state.model_dump(mode="json", warnings=False, exclude_none=True)
+ snapshot["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSION
+ return snapshot
def load_execution_state(snapshot: Mapping[str, Any]) -> GraphExecutionState:
@@ -25,10 +30,19 @@ def load_execution_state(snapshot: Mapping[str, Any]) -> GraphExecutionState:
if not isinstance(snapshot, Mapping):
raise TypeError("Execution state snapshot must be a mapping")
- if "version" not in snapshot:
+ if "version" not in snapshot and "execution_state_version" not in snapshot:
return GraphExecutionState.model_validate(snapshot, strict=False)
- version = snapshot["version"]
+ if "version" in snapshot:
+ version = snapshot["version"]
+ payload = snapshot.get("state")
+ if not isinstance(payload, Mapping):
+ raise ValueError("Versioned execution state snapshot must contain a mapping in 'state'")
+ else:
+ version = snapshot["execution_state_version"]
+ payload = dict(snapshot)
+ payload.pop("execution_state_version", None)
+
if isinstance(version, bool) or not isinstance(version, int):
raise ValueError("Execution state snapshot version must be an integer")
if version > CURRENT_EXECUTION_STATE_VERSION:
@@ -42,7 +56,4 @@ def load_execution_state(snapshot: Mapping[str, Any]) -> GraphExecutionState:
f"{CURRENT_EXECUTION_STATE_VERSION}"
)
- state = snapshot.get("state")
- if not isinstance(state, Mapping):
- raise ValueError("Versioned execution state snapshot must contain a mapping in 'state'")
- return GraphExecutionState.model_validate(state, strict=False)
+ return GraphExecutionState.model_validate(payload, strict=False)
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index e2746b1b11..24ee388deb 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -2584,6 +2584,8 @@ class ExecutionToken(BaseModel):
port: str = Field(description="Output port name")
frame: ExecutionFrame = Field(description="Frame that produced the token")
value: Any = Field(description="Output port value")
+ token_kind: Literal["data", "activation", "stream_end"] = Field(default="data")
+ sequence: int | None = Field(default=None, ge=0)
model_config = ConfigDict(extra="allow")
@@ -4435,7 +4437,7 @@ class GraphExecutionState(BaseModel):
raise ValueError("Execution effect ports do not match prepared graph edge")
def _build_execution_tokens(
- self, execution_ref: ExecutionReference, output: BaseInvocationOutput
+ self, execution_ref: ExecutionReference, output: BaseInvocationOutput, effects: Iterable[Any] = ()
) -> dict[str, ExecutionToken]:
tokens: dict[str, ExecutionToken] = {}
output_fields = type(output).model_fields
@@ -4451,6 +4453,32 @@ class GraphExecutionState(BaseModel):
frame=execution_ref.frame,
value=copydeep(getattr(output, port)),
)
+ for effect in effects:
+ if self._value_from_object(effect, "kind", "effect_type", "type") != "emit":
+ continue
+ token = self._value_from_object(effect, "token")
+ port = self._value_from_object(token, "field", "port", "output", "output_name")
+ if port in (None, LOOP_LINKAGE_FIELD):
+ continue
+ token_node_id = self._value_from_object(token, "node_id", "invocation_id", "source_node_id")
+ if token_node_id != execution_ref.exec_node_id:
+ raise ValueError("Execution token is not owned by execution reference")
+ token_value = self._value_from_object(effect, "value")
+ if token_value is None:
+ token_value = self._value_from_object(token, "value")
+ token_kind = self._value_from_object(token, "token_kind") or "data"
+ sequence = self._value_from_object(token, "sequence")
+ token_id = f"{execution_ref.reference_id}:{port}:{sequence if sequence is not None else 'effect'}"
+ tokens[token_id] = ExecutionToken(
+ token_id=token_id,
+ reference_id=execution_ref.reference_id,
+ owner_node_id=execution_ref.exec_node_id,
+ port=port,
+ frame=execution_ref.frame,
+ value=copydeep(token_value),
+ token_kind=token_kind,
+ sequence=sequence,
+ )
return tokens
def apply(
@@ -4477,7 +4505,7 @@ class GraphExecutionState(BaseModel):
batch_values = self._value_from_object(effects, "effects")
effect_values = list(batch_values if batch_values is not None else effects)
self._validate_effects(ref, effect_values, effect_count)
- tokens = self._build_execution_tokens(ref, output_value)
+ tokens = self._build_execution_tokens(ref, output_value, effect_values)
# All validation above is side-effect free. Preserve complete() as the scheduler compatibility boundary.
finalized_outputs = self.complete(ref.exec_node_id, output_value)
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index 42e0199267..b607e12b8b 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -18,7 +18,7 @@ from invokeai.app.services.images.images_common import ImageDTO
from invokeai.app.services.invocation_services import InvocationServices
from invokeai.app.services.model_records.model_records_base import UnknownModelException
from invokeai.app.services.session_processor.session_processor_common import ProgressImage
-from invokeai.app.services.shared.execution_effects import ExecutionEffectsRecorder
+from invokeai.app.services.shared.execution_effects import ExecutionEffectsRecorder, ExecutionInterface
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.videos.videos_common import VideoDTO
from invokeai.app.services.wildcard_records.wildcard_records_common import build_wildcard_manager
@@ -961,10 +961,12 @@ class InvocationContext:
"""An internal API providing access to data about the current queue item and invocation. You probably shouldn't use this. It may change without warning."""
self._services = services
"""An internal API providing access to all application services. You probably shouldn't use this. It may change without warning."""
- self.execution_effects = execution_effects or ExecutionEffectsRecorder()
+ self.execution_effects = execution_effects or ExecutionEffectsRecorder(source_node_id=data.invocation.id)
"""Effects recorded during the current invocation run."""
self.effects = self.execution_effects
"""Alias for :attr:`execution_effects`."""
+ self.execution = ExecutionInterface(self.execution_effects)
+ """Restricted execution-effect recorder facade."""
def build_invocation_context(
@@ -994,6 +996,9 @@ def build_invocation_context(
boards = BoardsInterface(services=services, data=data)
wildcards = WildcardsInterface(services=services, data=data)
+ if execution_effects is None:
+ execution_effects = ExecutionEffectsRecorder(source_node_id=data.invocation.id)
+
ctx = InvocationContext(
images=images,
videos=videos,
diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.py
index fdf35cbc14..39112bd3b9 100644
--- a/tests/app/services/shared/test_execution_effects.py
+++ b/tests/app/services/shared/test_execution_effects.py
@@ -28,6 +28,7 @@ class ExecutionEffectsTestOutput(BaseInvocationOutput):
@invocation("execution_effects_test", version="1.0.0")
class ExecutionEffectsTestInvocation(BaseInvocation):
+ execution_effects_enabled = True
value: int = InputField(default=1)
calls: ClassVar[int] = 0
diff --git a/tests/app/services/shared/test_execution_state_migration.py b/tests/app/services/shared/test_execution_state_migration.py
index c5ac1b3bb4..e60011916a 100644
--- a/tests/app/services/shared/test_execution_state_migration.py
+++ b/tests/app/services/shared/test_execution_state_migration.py
@@ -1,5 +1,6 @@
import pytest
+from invokeai.app.invocations.math import AddInvocation
from invokeai.app.services.shared.execution_state_migration import (
CURRENT_EXECUTION_STATE_VERSION,
UnsupportedExecutionStateVersionError,
@@ -10,9 +11,14 @@ from invokeai.app.services.shared.graph import Graph, GraphExecutionState
def _make_state() -> GraphExecutionState:
+ graph = Graph()
+ graph.add_node(AddInvocation(id="node-id", a=1, b=2))
+ execution_graph = Graph()
+ execution_graph.add_node(AddInvocation(id="exec-node", a=1, b=2))
return GraphExecutionState(
id="state-id",
- graph=Graph(),
+ graph=graph,
+ execution_graph=execution_graph,
executed={"node-id"},
executed_history=["node-id"],
errors={"node-id": "failure"},
@@ -40,14 +46,25 @@ def test_dumps_and_loads_versioned_execution_state_envelope() -> None:
snapshot = dump_execution_state(state)
restored = load_execution_state(snapshot)
- assert snapshot["version"] == CURRENT_EXECUTION_STATE_VERSION
- assert set(snapshot) == {"version", "state"}
- assert restored.model_dump(mode="json", warnings=False, exclude_none=True) == snapshot["state"]
+ assert snapshot["execution_state_version"] == CURRENT_EXECUTION_STATE_VERSION
+ assert "state" not in snapshot
+ expected = dict(snapshot)
+ expected.pop("execution_state_version")
+ assert restored.model_dump(mode="json", warnings=False, exclude_none=True) == expected
+
+
+def test_loads_temporary_versioned_envelope() -> None:
+ state = _make_state()
+ raw = state.model_dump(mode="json", warnings=False, exclude_none=True)
+
+ restored = load_execution_state({"version": CURRENT_EXECUTION_STATE_VERSION, "state": raw})
+
+ assert restored.id == state.id
def test_rejects_future_execution_state_versions() -> None:
snapshot = dump_execution_state(_make_state())
- snapshot["version"] = CURRENT_EXECUTION_STATE_VERSION + 1
+ snapshot["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSION + 1
with pytest.raises(UnsupportedExecutionStateVersionError, match="newer than supported"):
load_execution_state(snapshot)