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.

Fix execution effect persistence and dispatch

JPPhoto146852346452
diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.py
index c19570a762..ee6b34d2da 100644
--- a/invokeai/app/invocations/baseinvocation.py
+++ b/invokeai/app/invocations/baseinvocation.py
@@ -9,6 +9,7 @@ import types
import typing
import warnings
from abc import ABC, abstractmethod
+from copy import copy
from enum import Enum
from functools import lru_cache
from inspect import signature
@@ -53,6 +54,29 @@ if TYPE_CHECKING:
logger = InvokeAILogger.get_logger()
+class _InvocationCacheBypass:
+ """Cache facade that makes every lookup miss and suppresses writes."""
+
+ def __init__(self, cache: Any) -> None:
+ self._cache = cache
+
+ def get(self, key: int | str) -> None:
+ return None
+
+ def save(self, key: int | str, invocation_output: BaseInvocationOutput) -> None:
+ return None
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._cache, name)
+
+
+def _services_with_invocation_cache_bypassed(services: "InvocationServices") -> "InvocationServices":
+ """Copy services for one effectful dispatch with cache reads and writes disabled."""
+ effect_services = copy(services)
+ effect_services.invocation_cache = _InvocationCacheBypass(services.invocation_cache)
+ return effect_services
+
+
class InvalidVersionError(ValueError):
pass
@@ -269,7 +293,9 @@ class BaseInvocation(ABC, BaseModel):
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.
+ effects. The overridable ``invoke_internal()`` still runs, but receives
+ a per-dispatch cache facade that always misses and suppresses writes.
+ Overrides must access the cache through the supplied services object.
"""
if not self.execution_effects_enabled:
return InvocationRunResult(output=self.invoke_internal(context, services), effects=())
@@ -279,7 +305,7 @@ class BaseInvocation(ABC, BaseModel):
previous_skip_cache = getattr(context, "_skip_invocation_cache", False)
context._skip_invocation_cache = True
try:
- output = self.invoke_internal(context, services)
+ output = self.invoke_internal(context, _services_with_invocation_cache_bypassed(services))
finally:
context._skip_invocation_cache = previous_skip_cache
return InvocationRunResult(output=output, effects=context.execution_effects.snapshot())
diff --git a/invokeai/app/services/shared/execution_effects.py b/invokeai/app/services/shared/execution_effects.py
index 0e1b2d3432..6a60a0eb40 100644
--- a/invokeai/app/services/shared/execution_effects.py
+++ b/invokeai/app/services/shared/execution_effects.py
@@ -10,14 +10,25 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Literal, Union
-from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
-
-from invokeai.app.util.misc import uuid_string
+from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, field_validator, model_validator
+from pydantic_core import PydanticSerializationError
if TYPE_CHECKING:
from invokeai.app.invocations.baseinvocation import BaseInvocationOutput
+_JSON_SERIALIZER = TypeAdapter(Any)
+
+
+def _validate_json_serializable(value: Any) -> Any:
+ """Reject values that cannot survive GraphExecutionState JSON persistence."""
+ try:
+ _JSON_SERIALIZER.dump_python(value, mode="json", warnings="error")
+ except (PydanticSerializationError, TypeError, ValueError) as exc:
+ raise ValueError("must be JSON-serializable") from exc
+ return value
+
+
def _normalize_aliases(value: Any, aliases: dict[str, tuple[str, ...]]) -> Any:
if not isinstance(value, dict):
return value
@@ -46,7 +57,7 @@ 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.")
- value: Any | None = Field(default=None, description="The typed value carried by this token.")
+ value: Any | None = Field(default=None, description="The JSON-serializable 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."
@@ -81,6 +92,11 @@ class ExecutionToken(_ExecutionModel):
raise ValueError("frame values must not be blank")
return value
+ @field_validator("value")
+ @classmethod
+ def _reject_unserializable_value(cls, value: Any | None) -> Any | None:
+ return _validate_json_serializable(value)
+
@property
def invocation_id(self) -> str:
return self.node_id
@@ -125,7 +141,9 @@ 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 (
@@ -218,6 +236,8 @@ class SetValueEffect(ExecutionEffect):
target: ExecutionRef
value: Any
+ _validate_value = field_validator("value")(_validate_json_serializable)
+
class AddEdgeEffect(ExecutionEffect):
kind: Literal["add_edge"] = "add_edge"
@@ -236,6 +256,8 @@ class EmitEffect(ExecutionEffect):
token: ExecutionToken
value: Any | None = None
+ _validate_value = field_validator("value")(_validate_json_serializable)
+
class CloseStreamEffect(ExecutionEffect):
kind: Literal["close_stream"] = "close_stream"
@@ -255,14 +277,16 @@ class SpawnExecutionEffect(ExecutionEffect):
def _reject_missing_graph(cls, value: Any) -> Any:
if value is None:
raise ValueError("spawn graph must not be None")
- return value
+ return _validate_json_serializable(value)
@field_validator("inputs")
@classmethod
def _validate_input_names(cls, value: dict[str, Any]) -> dict[str, Any]:
if any(not name.strip() for name in value):
raise ValueError("spawn input names must not be blank")
- return value
+ return _validate_json_serializable(value)
+
+ _validate_authorization_context = field_validator("authorization_context")(_validate_json_serializable)
class AwaitEffect(ExecutionEffect):
@@ -293,6 +317,10 @@ RemoveExecutionEdgeEffect = RemoveEdgeEffect
EmitExecutionEffect = EmitEffect
+class UnsupportedExecutionEffectError(RuntimeError):
+ """Raised when the current graph dispatcher cannot apply an effect kind."""
+
+
class ExecutionInterface:
"""Restricted recorder facade exposed to invocation code."""
@@ -319,7 +347,7 @@ class ExecutionInterface:
node_id=self._recorder.source_node_id,
field=field,
value=value,
- frame=frame or self._recorder.frame_path,
+ frame=frame if frame is not None else self._recorder.frame_path,
token_kind=token_kind,
sequence=sequence,
),
@@ -333,7 +361,7 @@ class ExecutionInterface:
token=ExecutionToken(
node_id=self._recorder.source_node_id,
field=field,
- frame=frame or self._recorder.frame_path,
+ frame=frame if frame is not None else self._recorder.frame_path,
token_kind="stream_end",
)
)
@@ -347,31 +375,13 @@ class ExecutionInterface:
child_execution_id: str | None = None,
authorization_context: dict[str, Any] | None = None,
) -> "ChildExecutionHandle":
- owner = ExecutionRef(execution_node_id=self._recorder.source_node_id, frame_path=self._recorder.frame_path)
- handle = ChildExecutionHandle(
- child_execution_id=child_execution_id or uuid_string(),
- parent_execution_id=self._recorder.source_node_id,
- authorization_context=authorization_context,
- )
- self._recorder.record(
- SpawnExecutionEffect(
- execution_ref=owner,
- parent=owner,
- graph=graph,
- inputs=inputs,
- child_execution_id=handle.child_execution_id,
- authorization_context=handle.authorization_context,
- )
- )
- return handle
+ raise UnsupportedExecutionEffectError("Execution effect kind 'spawn_execution' is not supported")
def await_dependency(self, dependency: ExecutionRef) -> None:
- owner = ExecutionRef(execution_node_id=self._recorder.source_node_id, frame_path=self._recorder.frame_path)
- self._recorder.record(AwaitEffect(execution_ref=owner, dependency=dependency))
+ raise UnsupportedExecutionEffectError("Execution effect kind 'await' is not supported")
def fail(self, message: str) -> None:
- owner = ExecutionRef(execution_node_id=self._recorder.source_node_id, frame_path=self._recorder.frame_path)
- self._recorder.record(FailEffect(execution_ref=owner, message=message))
+ raise UnsupportedExecutionEffectError("Execution effect kind 'fail' is not supported")
def authorize_workflow(self, workflow_id: str) -> Any:
if self._authorize_workflow is None:
@@ -386,6 +396,8 @@ class ChildExecutionHandle(_ExecutionModel):
parent_execution_id: str = Field(min_length=1)
authorization_context: dict[str, Any] | None = None
+ _validate_authorization_context = field_validator("authorization_context")(_validate_json_serializable)
+
@model_validator(mode="before")
@classmethod
def _accept_compatibility_names(cls, value: Any) -> Any:
@@ -447,6 +459,10 @@ class ExecutionEffectsRecorder:
def record(self, effect: ExecutionEffect) -> None:
if not isinstance(effect, ExecutionEffect):
raise TypeError(f"Expected ExecutionEffect, got {type(effect).__name__}")
+ try:
+ effect.model_dump(mode="json", warnings="error")
+ except (PydanticSerializationError, TypeError, ValueError) as exc:
+ raise ValueError("Execution effect must be JSON-serializable") from exc
self._effects.append(effect)
record_effect = record
diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.py
index 7a53f9553b..da7e9ad234 100644
--- a/tests/app/services/shared/test_execution_effects.py
+++ b/tests/app/services/shared/test_execution_effects.py
@@ -15,6 +15,8 @@ from invokeai.app.services.shared.execution_effects import (
AddEdgeEffect,
AwaitEffect,
ChildExecutionHandle,
+ CloseStreamEffect,
+ EmitEffect,
ExecutionEffectsRecorder,
ExecutionInterface,
ExecutionRef,
@@ -22,7 +24,10 @@ from invokeai.app.services.shared.execution_effects import (
FailEffect,
SetValueEffect,
SpawnExecutionEffect,
+ UnsupportedExecutionEffectError,
)
+from invokeai.app.services.shared.execution_state_migration import dump_execution_state
+from invokeai.app.services.shared.graph import Graph, GraphExecutionState
from invokeai.app.services.shared.invocation_context import InvocationContext
@@ -48,6 +53,29 @@ class ExecutionEffectsTestInvocation(BaseInvocation):
return ExecutionEffectsTestOutput(value=self.value)
+@invocation("execution_effects_override_test", version="1.0.0")
+class ExecutionEffectsOverrideInvocation(BaseInvocation):
+ execution_effects_enabled = True
+ value: int = InputField(default=1)
+ calls: ClassVar[int] = 0
+
+ def invoke(self, context: InvocationContext) -> ExecutionEffectsTestOutput:
+ type(self).calls += 1
+ context.effects.record(
+ SetValueEffect(
+ target=ExecutionRef(node_id=self.id, field="value"),
+ value=self.value,
+ )
+ )
+ return ExecutionEffectsTestOutput(value=self.value)
+
+ def invoke_internal(self, context: InvocationContext, services: MagicMock) -> ExecutionEffectsTestOutput:
+ cached_value = services.invocation_cache.get("override-cache-key")
+ if cached_value is not None:
+ return cached_value
+ return self.invoke(context)
+
+
def _context() -> InvocationContext:
context = object.__new__(InvocationContext)
context.execution_effects = ExecutionEffectsRecorder()
@@ -84,26 +112,44 @@ def test_execution_ref_identity_aliases_are_safe_without_token() -> None:
assert ref.output_name == ""
-def test_spawn_returns_validated_child_handle_and_records_owner() -> None:
+def test_execution_interface_rejects_unsupported_lifecycle_effects() -> None:
recorder = ExecutionEffectsRecorder(source_node_id="parent")
execution = ExecutionInterface(recorder)
- handle = execution.spawn(
- graph={"nodes": {}},
- inputs={"value": {"items": [1, True, None]}},
- authorization_context={"user_id": "user"},
- )
+ with pytest.raises(UnsupportedExecutionEffectError, match="not supported"):
+ execution.spawn(graph={"nodes": {}}, inputs={})
+ with pytest.raises(UnsupportedExecutionEffectError, match="not supported"):
+ execution.await_dependency(ExecutionRef(execution_node_id="child"))
+ with pytest.raises(UnsupportedExecutionEffectError, match="not supported"):
+ execution.fail("failed")
+
+ assert recorder.snapshot() == ()
+
+
+def test_execution_interface_spawn_is_guarded() -> None:
+ recorder = ExecutionEffectsRecorder(source_node_id="parent")
+ execution = ExecutionInterface(recorder)
+
+ with pytest.raises(UnsupportedExecutionEffectError):
+ execution.spawn(
+ graph={"nodes": {}},
+ inputs={"value": {"items": [1, True, None]}},
+ authorization_context={"user_id": "user"},
+ )
+
- assert isinstance(handle, ChildExecutionHandle)
- assert handle.child_execution_id
- assert handle.parent_execution_id == "parent"
- assert handle.authorization_context == {"user_id": "user"}
- assert isinstance(recorder.snapshot()[0], SpawnExecutionEffect)
- effect = recorder.snapshot()[0]
- assert isinstance(effect, SpawnExecutionEffect)
- assert effect.parent == effect.execution_ref
- assert effect.child_execution_id == handle.child_execution_id
- assert effect.authorization_context == handle.authorization_context
+def test_execution_interface_preserves_explicit_empty_frame() -> None:
+ recorder = ExecutionEffectsRecorder(source_node_id="node", frame_path=(2,))
+ execution = ExecutionInterface(recorder)
+
+ execution.emit("value", 1, frame=())
+ execution.close_stream("value", frame=())
+
+ emit_effect, close_effect = recorder.snapshot()
+ assert isinstance(emit_effect, EmitEffect)
+ assert isinstance(close_effect, CloseStreamEffect)
+ assert emit_effect.token.frame == ()
+ assert close_effect.token.frame == ()
@pytest.mark.parametrize(
@@ -128,10 +174,13 @@ def test_child_execution_handle_rejects_invalid_identity_or_authorization(value:
],
)
def test_spawn_rejects_invalid_inputs(graph: object, inputs: object) -> None:
- execution = ExecutionInterface(ExecutionEffectsRecorder(source_node_id="parent"))
-
with pytest.raises((TypeError, ValidationError)):
- execution.spawn(graph, inputs) # type: ignore[arg-type]
+ SpawnExecutionEffect(
+ parent=ExecutionRef(execution_node_id="parent"),
+ graph=graph,
+ inputs=inputs, # type: ignore[arg-type]
+ child_execution_id="child",
+ )
def test_recorder_drain_returns_and_clears_effects() -> None:
@@ -143,13 +192,45 @@ def test_recorder_drain_returns_and_clears_effects() -> None:
assert recorder.snapshot() == ()
-def test_set_value_effect_accepts_nested_and_runtime_values() -> None:
+def test_effect_values_accept_json_serializable_values_and_reject_runtime_values() -> None:
target = ExecutionRef(node_id="node", field="value")
nested_value = {"items": [1, True, None, {"name": "value"}]}
assert SetValueEffect(target=target, value=nested_value).value == nested_value
- runtime_value = object()
- assert SetValueEffect(target=target, value=runtime_value).value is runtime_value
+ with pytest.raises(ValidationError, match="JSON-serializable"):
+ SetValueEffect(target=target, value=object())
+ with pytest.raises(ValidationError, match="JSON-serializable"):
+ EmitEffect(token=ExecutionToken(node_id="node", field="value"), value=object())
+ with pytest.raises(ValidationError, match="JSON-serializable"):
+ ExecutionToken(node_id="node", field="value", value=object())
+ with pytest.raises(ValidationError, match="JSON-serializable"):
+ SpawnExecutionEffect(parent=ExecutionRef(execution_node_id="node"), graph=object(), child_execution_id="child")
+ with pytest.raises(ValidationError, match="JSON-serializable"):
+ SpawnExecutionEffect(
+ parent=ExecutionRef(execution_node_id="node"),
+ graph={},
+ inputs={"value": object()},
+ child_execution_id="child",
+ )
+ with pytest.raises(ValidationError, match="JSON-serializable"):
+ SpawnExecutionEffect(
+ parent=ExecutionRef(execution_node_id="node"),
+ graph={},
+ authorization_context={"user": object()},
+ child_execution_id="child",
+ )
+
+
+def test_effect_values_survive_execution_state_json_dump() -> None:
+ effect = SetValueEffect(
+ target=ExecutionRef(node_id="node", field="value"),
+ value={"items": [1, True, None, {"name": "value"}]},
+ )
+ state = GraphExecutionState(graph=Graph(), execution_effects={"reference": [effect]})
+
+ snapshot = dump_execution_state(state)
+
+ assert snapshot["execution_effects"]["reference"][0]["value"] == effect.value
def test_set_value_effect_requires_a_value() -> None:
@@ -157,18 +238,18 @@ def test_set_value_effect_requires_a_value() -> None:
SetValueEffect(target=ExecutionRef(node_id="node", field="value"))
-def test_recorder_created_control_effects_carry_owner_refs() -> None:
+def test_lifecycle_effect_models_validate_owner_refs() -> None:
recorder = ExecutionEffectsRecorder(source_node_id="parent")
- execution = ExecutionInterface(recorder)
-
- execution.await_dependency(ExecutionRef(execution_node_id="child"))
- execution.fail("failed")
-
- await_effect, fail_effect = recorder.snapshot()
+ await_effect = AwaitEffect(
+ execution_ref=ExecutionRef(execution_node_id="parent"),
+ dependency=ExecutionRef(execution_node_id="child"),
+ )
+ fail_effect = FailEffect(execution_ref=ExecutionRef(execution_node_id="parent"), message="failed")
+ recorder.record(await_effect)
+ recorder.record(fail_effect)
assert isinstance(await_effect, AwaitEffect)
assert isinstance(fail_effect, FailEffect)
- assert await_effect.execution_ref == ExecutionRef(execution_node_id="parent")
- assert fail_effect.execution_ref == ExecutionRef(execution_node_id="parent")
+ assert recorder.snapshot() == (await_effect, fail_effect)
@pytest.mark.parametrize(
@@ -207,6 +288,11 @@ def test_recorder_rejects_untyped_values_and_returns_copy() -> None:
with pytest.raises(TypeError, match="Expected ExecutionEffect"):
recorder.record("not an effect") # type: ignore[arg-type]
+ invalid_effect = effect.model_copy(update={"value": object()})
+ with pytest.raises(ValueError, match="JSON-serializable"):
+ recorder.record(invalid_effect)
+ assert recorder.snapshot() == (effect,)
+
def test_effectful_invoke_bypasses_output_only_cache() -> None:
ExecutionEffectsTestInvocation.calls = 0
@@ -237,3 +323,18 @@ def test_effectful_invoke_clears_stale_effects() -> None:
result = ExecutionEffectsTestInvocation(id="node", value=2).invoke_internal_with_effects(context, _services())
assert [effect.value for effect in result.effects if isinstance(effect, SetValueEffect)] == [2]
+
+
+def test_effectful_invoke_disables_cache_in_invoke_internal_override() -> None:
+ ExecutionEffectsOverrideInvocation.calls = 0
+ services = _services()
+ services.invocation_cache.get.return_value = ExecutionEffectsTestOutput(value=99)
+ invocation_instance = ExecutionEffectsOverrideInvocation(id="node", value=7, use_cache=True)
+
+ result = invocation_instance.invoke_internal_with_effects(_context(), services)
+
+ assert result.output == ExecutionEffectsTestOutput(value=7)
+ assert len(result.effects) == 1
+ assert ExecutionEffectsOverrideInvocation.calls == 1
+ assert invocation_instance.use_cache is True
+ services.invocation_cache.get.assert_not_called()