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): validate recorded effect ownership and child handles

JPPhoto7d55de461180
diff --git a/invokeai/app/services/shared/execution_effects.py b/invokeai/app/services/shared/execution_effects.py
index 32f078d3d4..e3fe6147f1 100644
--- a/invokeai/app/services/shared/execution_effects.py
+++ b/invokeai/app/services/shared/execution_effects.py
@@ -10,7 +10,9 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Literal, Union
-from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator, model_validator
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+
+from invokeai.app.util.misc import uuid_string
if TYPE_CHECKING:
from invokeai.app.invocations.baseinvocation import BaseInvocationOutput
@@ -176,11 +178,11 @@ class ExecutionRef(_ExecutionModel):
@property
def invocation_id(self) -> str:
- return self.token.node_id
+ return self.node_id
@property
def output_name(self) -> str:
- return self.token.field
+ return self.field
@property
def iteration_path(self) -> tuple[int | str, ...]:
@@ -191,6 +193,9 @@ class ExecutionEffect(_ExecutionModel):
"""Base type for a recorded execution effect."""
kind: str = Field(min_length=1)
+ execution_ref: ExecutionRef | None = Field(
+ default=None, description="The execution reference that owns this effect, when available."
+ )
@field_validator("kind")
@classmethod
@@ -203,7 +208,7 @@ class ExecutionEffect(_ExecutionModel):
class SetValueEffect(ExecutionEffect):
kind: Literal["set_value"] = "set_value"
target: ExecutionRef
- value: JsonValue
+ value: Any
class AddEdgeEffect(ExecutionEffect):
@@ -235,6 +240,20 @@ class SpawnExecutionEffect(ExecutionEffect):
graph: Any
inputs: dict[str, Any] = Field(default_factory=dict)
+ @field_validator("graph")
+ @classmethod
+ def _reject_missing_graph(cls, value: Any) -> Any:
+ if value is None:
+ raise ValueError("spawn graph must not be None")
+ return 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
+
class AwaitEffect(ExecutionEffect):
kind: Literal["await"] = "await"
@@ -310,20 +329,37 @@ class ExecutionInterface:
)
)
- def spawn(self, graph: Any, inputs: dict[str, Any]) -> None:
+ def spawn(
+ self,
+ graph: Any,
+ inputs: dict[str, Any],
+ *,
+ 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(
- parent=ExecutionRef(execution_node_id=self._recorder.source_node_id, frame_path=self._recorder.frame_path),
+ execution_ref=owner,
+ parent=owner,
graph=graph,
inputs=inputs,
)
)
+ return handle
def await_dependency(self, dependency: ExecutionRef) -> None:
- self._recorder.record(AwaitEffect(dependency=dependency))
+ 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))
def fail(self, message: str) -> None:
- self._recorder.record(FailEffect(message=message))
+ 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))
def authorize_workflow(self, workflow_id: str) -> Any:
if self._authorize_workflow is None:
@@ -331,6 +367,49 @@ class ExecutionInterface:
return self._authorize_workflow(workflow_id)
+class ChildExecutionHandle(_ExecutionModel):
+ """Validated identity and authorization metadata for a spawned child."""
+
+ child_execution_id: str = Field(min_length=1)
+ parent_execution_id: str = Field(min_length=1)
+ authorization_context: dict[str, Any] | None = None
+
+ @model_validator(mode="before")
+ @classmethod
+ def _accept_compatibility_names(cls, value: Any) -> Any:
+ return _normalize_aliases(
+ value,
+ {
+ "child_execution_id": ("child_id", "execution_id"),
+ "parent_execution_id": ("parent_id",),
+ "authorization_context": ("authorization", "auth_context"),
+ },
+ )
+
+ @field_validator("child_execution_id", "parent_execution_id")
+ @classmethod
+ def _reject_blank_ids(cls, value: str) -> str:
+ if not value.strip():
+ raise ValueError("must not be blank")
+ return value
+
+ @property
+ def child_id(self) -> str:
+ return self.child_execution_id
+
+ @property
+ def execution_id(self) -> str:
+ return self.child_execution_id
+
+ @property
+ def parent_id(self) -> str:
+ return self.parent_execution_id
+
+ @property
+ def authorization(self) -> dict[str, Any] | None:
+ return self.authorization_context
+
+
@dataclass(frozen=True)
class ExecutionEffectBatch:
effects: tuple[ExecutionEffect, ...]
@@ -363,6 +442,12 @@ class ExecutionEffectsRecorder:
def snapshot(self) -> tuple[ExecutionEffect, ...]:
return tuple(self._effects)
+ def drain(self) -> tuple[ExecutionEffect, ...]:
+ """Return all recorded effects and reset the recorder."""
+ effects = self.snapshot()
+ self.clear()
+ return effects
+
def batch(self) -> ExecutionEffectBatch:
return ExecutionEffectBatch(effects=self.snapshot())
diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.py
index 39112bd3b9..cfc72a2fff 100644
--- a/tests/app/services/shared/test_execution_effects.py
+++ b/tests/app/services/shared/test_execution_effects.py
@@ -13,10 +13,15 @@ from invokeai.app.invocations.baseinvocation import (
from invokeai.app.invocations.fields import InputField, OutputField
from invokeai.app.services.shared.execution_effects import (
AddEdgeEffect,
+ AwaitEffect,
+ ChildExecutionHandle,
+ ExecutionInterface,
ExecutionEffectsRecorder,
ExecutionRef,
ExecutionToken,
+ FailEffect,
SetValueEffect,
+ SpawnExecutionEffect,
)
from invokeai.app.services.shared.invocation_context import InvocationContext
@@ -67,6 +72,98 @@ def test_execution_token_and_ref_are_frame_aware() -> None:
assert ref.iteration_path == (2, 4)
+def test_execution_ref_identity_aliases_are_safe_without_token() -> None:
+ ref = ExecutionRef(execution_node_id="node")
+
+ assert ref.invocation_id == "node"
+ assert ref.output_name == ""
+
+
+def test_spawn_returns_validated_child_handle_and_records_owner() -> 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"},
+ )
+
+ 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
+
+
+ "value",
+ [
+ {"child_execution_id": "", "parent_execution_id": "parent"},
+ {"child_execution_id": "child", "parent_execution_id": ""},
+ {"child_execution_id": "child", "parent_execution_id": "parent", "authorization_context": ""},
+ ],
+)
+def test_child_execution_handle_rejects_invalid_identity_or_authorization(value: dict[str, object]) -> None:
+ with pytest.raises(ValidationError):
+ ChildExecutionHandle.model_validate(value)
+
+
+ "graph, inputs",
+ [
+ (None, {}),
+ ({"nodes": {}}, []),
+ ({"nodes": {}}, {"": 1}),
+ ],
+)
+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]
+
+
+def test_recorder_drain_returns_and_clears_effects() -> None:
+ recorder = ExecutionEffectsRecorder()
+ effect = SetValueEffect(target=ExecutionRef(node_id="node", field="value"), value=3)
+ recorder.record(effect)
+
+ assert recorder.drain() == (effect,)
+ assert recorder.snapshot() == ()
+
+
+def test_set_value_effect_accepts_nested_and_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
+
+
+def test_set_value_effect_requires_a_value() -> None:
+ with pytest.raises(ValidationError):
+ SetValueEffect(target=ExecutionRef(node_id="node", field="value"))
+
+
+def test_recorder_created_control_effects_carry_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()
+ 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")
+
+
@pytest.mark.parametrize(
"value",
[