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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(execution): add invocation effects recording
JPPhoto5895014c686e
diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.pyindex 351e22a88d..261d9efa5a 100644--- a/invokeai/app/invocations/baseinvocation.py+++ b/invokeai/app/invocations/baseinvocation.py@@ -41,6 +41,7 @@ from invokeai.app.invocations.fields import (migrate_model_ui_type,)from invokeai.app.services.config.config_default import get_config+from invokeai.app.services.shared.execution_effects import InvocationRunResultfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.app.util.metaenum import MetaEnumfrom invokeai.app.util.misc import uuid_string@@ -211,11 +212,7 @@ class BaseInvocation(ABC, BaseModel):"""Returns the invocation representation included in execution events."""return self- def invoke_internal(self, context: InvocationContext, services: "InvocationServices") -> BaseInvocationOutput:- """- Internal invoke method, calls `invoke()` after some prep.- Handles optional fields that are required to call `invoke()` and invocation cache.- """+ def _validate_invoke_fields(self) -> None:for field_name, field in type(self).model_fields.items():if not field.json_schema_extra or callable(field.json_schema_extra):# something has gone terribly awry, we should always have this and it should be a dict@@ -235,6 +232,13 @@ class BaseInvocation(ABC, BaseModel):elif input_ == Input.Any:raise MissingInputException(type(self).model_fields["type"].default, field_name)+ def invoke_internal(self, context: InvocationContext, services: "InvocationServices") -> BaseInvocationOutput:+ """+ Internal invoke method, calls `invoke()` after some prep.+ Handles optional fields that are required to call `invoke()` and invocation cache.+ """+ self._validate_invoke_fields()+# skip node cache codepath if it's disabledif services.configuration.node_cache_size == 0:return self.invoke(context)@@ -255,6 +259,23 @@ class BaseInvocation(ABC, BaseModel):services.logger.debug(f'Skipping invocation cache for "{self.get_type()}": {self.id}')return self.invoke(context)+ def invoke_internal_with_effects(+ self, context: InvocationContext, services: "InvocationServices"+ ) -> 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.+ """+ self._validate_invoke_fields()+ context.execution_effects.clear()+ if self.use_cache and services.configuration.node_cache_size != 0:+ services.logger.debug(f'Skipping invocation cache for effect recording for "{self.get_type()}": {self.id}')+ output = self.invoke(context)+ return InvocationRunResult(output=output, effects=context.execution_effects.snapshot())+id: str = Field(default_factory=uuid_string,description="The id of this instance of an invocation. Must be unique among all instances of invocations.",diff --git a/invokeai/app/services/shared/execution_effects.py b/invokeai/app/services/shared/execution_effects.pynew file mode 100644index 0000000000..67a3d6065e--- /dev/null+++ b/invokeai/app/services/shared/execution_effects.py@@ -0,0 +1,253 @@+"""Typed execution effects recorded while an invocation runs.++This module is deliberately independent of graph materialization. It provides+validated references and a per-invocation effect batch for the execution+engine migration.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Literal, Union++from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator, model_validator++if TYPE_CHECKING:+ from invokeai.app.invocations.baseinvocation import BaseInvocationOutput+++def _normalize_aliases(value: Any, aliases: dict[str, tuple[str, ...]]) -> Any:+ if not isinstance(value, dict):+ return value++ data = dict(value)+ for canonical, alternative_names in aliases.items():+ names = (canonical, *alternative_names)+ present = [name for name in names if name in data]+ if not present:+ continue+ if canonical not in data:+ data[canonical] = data[present[0]]+ if any(data[name] != data[canonical] for name in present if name != canonical):+ raise ValueError(f"Conflicting values for {canonical}")+ for name in alternative_names:+ data.pop(name, None)+ return data+++class _ExecutionModel(BaseModel):+ model_config = ConfigDict(extra="forbid", frozen=True)+++class ExecutionToken(_ExecutionModel):+ """Stable identity for one invocation output in one iteration frame."""++ 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.")++ @model_validator(mode="before")+ @classmethod+ def _accept_legacy_names(cls, value: Any) -> Any:+ return _normalize_aliases(+ value,+ {+ "node_id": ("invocation_id",),+ "field": ("port", "output", "output_name"),+ "frame": ("iteration_path", "frame_path"),+ },+ )++ @field_validator("node_id", "field")+ @classmethod+ def _reject_blank_names(cls, value: str) -> str:+ if not value.strip():+ raise ValueError("must not be blank")+ return value++ @field_validator("frame")+ @classmethod+ def _reject_negative_frame_parts(cls, value: tuple[int, ...]) -> tuple[int, ...]:+ if any(part < 0 for part in value):+ raise ValueError("frame values must be non-negative")+ return value++ @property+ def invocation_id(self) -> str:+ return self.node_id++ @property+ def port(self) -> str:+ return self.field++ @property+ def output_name(self) -> str:+ return self.field++ @property+ def iteration_path(self) -> tuple[int, ...]:+ return self.frame+++class ExecutionRef(_ExecutionModel):+ """Frame-aware reference to an execution token."""++ token: ExecutionToken+ scope: Literal["iteration", "final"] = "final"++ @model_validator(mode="before")+ @classmethod+ def _accept_token_fields(cls, value: Any) -> Any:+ 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")+ ):+ token_fields = {+ name: data.pop(name)+ for name in (+ "node_id",+ "invocation_id",+ "field",+ "port",+ "output",+ "output_name",+ "frame",+ "iteration_path",+ "frame_path",+ )+ if name in data+ }+ data["token"] = token_fields+ return data++ @property+ def node_id(self) -> str:+ return self.token.node_id++ @property+ def field(self) -> str:+ return self.token.field++ @property+ def frame(self) -> tuple[int, ...]:+ return self.token.frame++ @property+ def invocation_id(self) -> str:+ return self.token.node_id++ @property+ def output_name(self) -> str:+ return self.token.field++ @property+ def iteration_path(self) -> tuple[int, ...]:+ return self.token.frame+++class ExecutionEffect(_ExecutionModel):+ """Base type for a recorded execution effect."""++ kind: str = Field(min_length=1)++ @field_validator("kind")+ @classmethod+ def _reject_blank_kind(cls, value: str) -> str:+ if not value.strip():+ raise ValueError("must not be blank")+ return value+++class SetValueEffect(ExecutionEffect):+ kind: Literal["set_value"] = "set_value"+ target: ExecutionRef+ value: JsonValue+++class AddEdgeEffect(ExecutionEffect):+ kind: Literal["add_edge"] = "add_edge"+ source: ExecutionRef+ destination: ExecutionRef+++class RemoveEdgeEffect(ExecutionEffect):+ kind: Literal["remove_edge"] = "remove_edge"+ source: ExecutionRef+ destination: ExecutionRef+++class EmitEffect(ExecutionEffect):+ kind: Literal["emit"] = "emit"+ token: ExecutionToken+ value: JsonValue | None = None+++ExecutionEffectModel = Union[SetValueEffect, AddEdgeEffect, RemoveEdgeEffect, EmitEffect]++# Descriptive aliases keep call sites free to use execution-specific names.+SetExecutionValueEffect = SetValueEffect+AddExecutionEdgeEffect = AddEdgeEffect+RemoveExecutionEdgeEffect = RemoveEdgeEffect+EmitExecutionEffect = EmitEffect+++@dataclass(frozen=True)+class ExecutionEffectBatch:+ effects: tuple[ExecutionEffect, ...]++ def __iter__(self):+ return iter(self.effects)++ def __len__(self) -> int:+ return len(self.effects)++ def __bool__(self) -> bool:+ return bool(self.effects)+++class ExecutionEffectsRecorder:+ """Collects effects for one invocation run."""++ def __init__(self) -> None:+ self._effects: list[ExecutionEffect] = []++ def record(self, effect: ExecutionEffect) -> None:+ if not isinstance(effect, ExecutionEffect):+ raise TypeError(f"Expected ExecutionEffect, got {type(effect).__name__}")+ self._effects.append(effect)++ record_effect = record++ def snapshot(self) -> tuple[ExecutionEffect, ...]:+ return tuple(self._effects)++ def batch(self) -> ExecutionEffectBatch:+ return ExecutionEffectBatch(effects=self.snapshot())++ def clear(self) -> None:+ self._effects.clear()++ @property+ def effects(self) -> tuple[ExecutionEffect, ...]:+ return self.snapshot()+++ExecutionEffectRecorder = ExecutionEffectsRecorder+++@dataclass(frozen=True)+class InvocationRunResult:+ """Invocation output plus effects recorded during that run."""++ output: "BaseInvocationOutput"+ effects: tuple[ExecutionEffect, ...]++ @property+ def invocation_output(self) -> "BaseInvocationOutput":+ return self.output++ @property+ def effect_batch(self) -> ExecutionEffectBatch:+ return ExecutionEffectBatch(effects=self.effects)diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.pyindex 35ee5e1191..42e0199267 100644--- a/invokeai/app/services/shared/invocation_context.py+++ b/invokeai/app/services/shared/invocation_context.py@@ -18,6 +18,7 @@ from invokeai.app.services.images.images_common import ImageDTOfrom invokeai.app.services.invocation_services import InvocationServicesfrom invokeai.app.services.model_records.model_records_base import UnknownModelExceptionfrom invokeai.app.services.session_processor.session_processor_common import ProgressImage+from invokeai.app.services.shared.execution_effects import ExecutionEffectsRecorderfrom invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirectionfrom invokeai.app.services.videos.videos_common import VideoDTOfrom invokeai.app.services.wildcard_records.wildcard_records_common import build_wildcard_manager@@ -934,6 +935,7 @@ class InvocationContext:wildcards: WildcardsInterface,data: InvocationContextData,services: InvocationServices,+ execution_effects: Optional[ExecutionEffectsRecorder] = None,) -> None:self.images = images"""Methods to save, get and update images and their metadata."""@@ -959,12 +961,17 @@ 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()+ """Effects recorded during the current invocation run."""+ self.effects = self.execution_effects+ """Alias for :attr:`execution_effects`."""def build_invocation_context(services: InvocationServices,data: InvocationContextData,is_canceled: Callable[[], bool],+ execution_effects: Optional[ExecutionEffectsRecorder] = None,) -> InvocationContext:"""Builds the invocation context for a specific invocation execution.@@ -1000,6 +1007,7 @@ def build_invocation_context(services=services,boards=boards,wildcards=wildcards,+ execution_effects=execution_effects,)return ctxdiff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.pynew file mode 100644index 0000000000..fdf35cbc14--- /dev/null+++ b/tests/app/services/shared/test_execution_effects.py@@ -0,0 +1,134 @@+from typing import ClassVar+from unittest.mock import MagicMock++import pytest+from pydantic import ValidationError++from invokeai.app.invocations.baseinvocation import (+ BaseInvocation,+ BaseInvocationOutput,+ invocation,+ invocation_output,+)+from invokeai.app.invocations.fields import InputField, OutputField+from invokeai.app.services.shared.execution_effects import (+ AddEdgeEffect,+ ExecutionEffectsRecorder,+ ExecutionRef,+ ExecutionToken,+ SetValueEffect,+)+from invokeai.app.services.shared.invocation_context import InvocationContext+++@invocation_output("execution_effects_test_output")+class ExecutionEffectsTestOutput(BaseInvocationOutput):+ value: int = OutputField()+++@invocation("execution_effects_test", version="1.0.0")+class ExecutionEffectsTestInvocation(BaseInvocation):+ 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 _context() -> InvocationContext:+ context = object.__new__(InvocationContext)+ context.execution_effects = ExecutionEffectsRecorder()+ context.effects = context.execution_effects+ return context+++def _services(cache_size: int = 1) -> MagicMock:+ services = MagicMock()+ services.configuration.node_cache_size = cache_size+ return services+++def test_execution_token_and_ref_are_frame_aware() -> None:+ token = ExecutionToken(invocation_id="node", port="value", iteration_path=(2, 4))+ ref = ExecutionRef(token=token, scope="iteration")++ assert token.node_id == "node"+ assert token.field == "value"+ assert token.frame == (2, 4)+ assert ref.invocation_id == "node"+ assert ref.iteration_path == (2, 4)+++ "value",+ [+ {"node_id": "", "field": "value"},+ {"node_id": "node", "field": ""},+ {"node_id": "node", "field": "value", "frame": (-1,)},+ {"node_id": "node", "field": "value", "frame": (1,), "iteration_path": (2,)},+ ],+)+def test_execution_token_rejects_malformed_identity(value: dict[str, object]) -> None:+ with pytest.raises(ValidationError):+ ExecutionToken.model_validate(value)+++def test_effect_models_validate_typed_refs() -> None:+ source = ExecutionRef(node_id="source", field="value")+ destination = ExecutionRef(node_id="destination", field="input")++ effect = AddEdgeEffect(source=source, destination=destination)+ assert effect.kind == "add_edge"++ with pytest.raises(ValidationError):+ AddEdgeEffect(source=source, destination={"node_id": "destination"})+++def test_recorder_rejects_untyped_values_and_returns_copy() -> None:+ recorder = ExecutionEffectsRecorder()+ effect = SetValueEffect(target=ExecutionRef(node_id="node", field="value"), value=3)++ recorder.record(effect)+ effects = recorder.snapshot()++ assert effects == (effect,)+ with pytest.raises(TypeError, match="Expected ExecutionEffect"):+ recorder.record("not an effect") # type: ignore[arg-type]+++def test_effectful_invoke_bypasses_output_only_cache() -> None:+ ExecutionEffectsTestInvocation.calls = 0+ services = _services()+ cached_output = ExecutionEffectsTestOutput(value=99)+ services.invocation_cache.get.return_value = cached_output+ invocation_instance = ExecutionEffectsTestInvocation(id="node", value=7, use_cache=True)++ ordinary_output = invocation_instance.invoke_internal(_context(), services)+ assert ordinary_output == cached_output+ assert ExecutionEffectsTestInvocation.calls == 0+ services.invocation_cache.get.assert_called_once()++ services.invocation_cache.reset_mock()+ result = invocation_instance.invoke_internal_with_effects(_context(), services)++ assert result.output == ExecutionEffectsTestOutput(value=7)+ assert len(result.effects) == 1+ assert result.effects[0].kind == "set_value"+ assert ExecutionEffectsTestInvocation.calls == 1+ services.invocation_cache.get.assert_not_called()+ services.invocation_cache.save.assert_not_called()+++def test_effectful_invoke_clears_stale_effects() -> None:+ context = _context()+ context.effects.record(SetValueEffect(target=ExecutionRef(node_id="stale", field="value"), value=0))+ 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]