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(graph): accept subclass collector items for union item types

unmarco796b0f83b54c
diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.py
index 0ccb15e11f..1430c1b072 100644
--- a/invokeai/app/services/shared/graph_validation.py
+++ b/invokeai/app/services/shared/graph_validation.py
@@ -5,6 +5,7 @@ import weakref
from contextvars import ContextVar
from dataclasses import dataclass
from functools import wraps
+from types import UnionType
from typing import (
TYPE_CHECKING,
Any,
@@ -2336,9 +2337,11 @@ class Graph(BaseModel):
def _collector_item_matches(input_root_type: Any, item_type: Any) -> bool:
if is_any(item_type) or is_union_subtype(input_root_type, item_type):
return True
- return (
- isinstance(input_root_type, type) and isinstance(item_type, type) and issubclass(input_root_type, item_type)
- )
+ if not isinstance(input_root_type, type):
+ return False
+ # A union item type (e.g. `list[Union[Base, str]]`) matches a subclass of any of its members.
+ candidates = get_args(item_type) if get_origin(item_type) in (Union, UnionType) else (item_type,)
+ return any(isinstance(c, type) and issubclass(input_root_type, c) for c in candidates)
def _validate_downstream_collector_outputs(
self,
diff --git a/tests/test_node_graph.py b/tests/test_node_graph.py
index d0e343a1fa..5e13b4544e 100644
--- a/tests/test_node_graph.py
+++ b/tests/test_node_graph.py
@@ -49,15 +49,18 @@ from invokeai.app.services.shared.graph import (
)
from tests.test_nodes import (
AnyTypeTestInvocation,
+ DerivedFieldTestInvocation,
ImageToImageTestInvocation,
ListPassThroughInvocation,
OptionalCollectionTestInvocation,
+ Pep604UnionItemCollectionTestInvocation,
PolymorphicStringTestInvocation,
PromptCollectionTestInvocation,
PromptTestInvocation,
PromptTestInvocationOutput,
TextToImageTestInvocation,
UnionCollectionTestInvocation,
+ UnionItemCollectionTestInvocation,
get_single_output_from_session,
run_session_with_mock_context,
)
@@ -2244,6 +2247,38 @@ def test_graph_collector_accepts_matching_items_for_optional_list_input():
g.add_edge(create_edge("collect", "collection", "target", "value"))
+# Collection inputs whose item type is a union, spelled with typing.Union and with PEP 604.
+UNION_ITEM_COLLECTION_TARGETS = [
+ pytest.param(UnionItemCollectionTestInvocation, id="typing-union"),
+ pytest.param(Pep604UnionItemCollectionTestInvocation, id="pep604-union"),
+]
+
+
[email protected]("target_type", UNION_ITEM_COLLECTION_TARGETS)
+def test_graph_collector_accepts_subclass_items_for_union_item_collection_input(target_type):
+ g = Graph()
+ g.add_node(DerivedFieldTestInvocation(id="1"))
+ g.add_node(DerivedFieldTestInvocation(id="2"))
+ g.add_node(CollectInvocation(id="collect"))
+ g.add_node(target_type(id="target"))
+ g.add_edge(create_edge("1", "value", "collect", "item"))
+ g.add_edge(create_edge("2", "value", "collect", "item"))
+
+ g.add_edge(create_edge("collect", "collection", "target", "value"))
+
+
[email protected]("target_type", UNION_ITEM_COLLECTION_TARGETS)
+def test_graph_collector_rejects_mismatched_items_for_union_item_collection_input(target_type):
+ g = Graph()
+ g.add_node(IntegerInvocation(id="1", value=1))
+ g.add_node(CollectInvocation(id="collect"))
+ g.add_node(target_type(id="target"))
+ g.add_edge(create_edge("1", "value", "collect", "item"))
+
+ with pytest.raises(InvalidEdgeError, match="matching type"):
+ g.add_edge(create_edge("collect", "collection", "target", "value"))
+
+
def test_graph_connects_iterator():
g = Graph()
n1 = ListPassThroughInvocation(id="1")
diff --git a/tests/test_nodes.py b/tests/test_nodes.py
index aaf50f35fc..71d3ffc121 100644
--- a/tests/test_nodes.py
+++ b/tests/test_nodes.py
@@ -1,6 +1,8 @@
from typing import Any, Callable, Union
from unittest.mock import MagicMock
+from pydantic import BaseModel
+
from invokeai.app.invocations.baseinvocation import (
BaseInvocation,
BaseInvocationOutput,
@@ -150,6 +152,41 @@ class OptionalCollectionTestInvocation(BaseInvocation):
return PromptCollectionTestInvocationOutput(collection=self.value or [])
+class BaseTestField(BaseModel):
+ name: str = ""
+
+
+class DerivedTestField(BaseTestField):
+ pass
+
+
+@invocation_output("test_derived_field_output")
+class DerivedFieldTestInvocationOutput(BaseInvocationOutput):
+ value: DerivedTestField = OutputField()
+
+
+@invocation("test_derived_field", version="1.0.0")
+class DerivedFieldTestInvocation(BaseInvocation):
+ def invoke(self, context: InvocationContext) -> DerivedFieldTestInvocationOutput:
+ return DerivedFieldTestInvocationOutput(value=DerivedTestField())
+
+
+@invocation("test_union_item_collection", version="1.0.0")
+class UnionItemCollectionTestInvocation(BaseInvocation):
+ value: list[Union[BaseTestField, str]] = InputField(default=[])
+
+ def invoke(self, context: InvocationContext) -> PromptCollectionTestInvocationOutput:
+ return PromptCollectionTestInvocationOutput(collection=[])
+
+
+@invocation("test_pep604_union_item_collection", version="1.0.0")
+class Pep604UnionItemCollectionTestInvocation(BaseInvocation):
+ value: list[BaseTestField | str] = InputField(default=[])
+
+ def invoke(self, context: InvocationContext) -> PromptCollectionTestInvocationOutput:
+ return PromptCollectionTestInvocationOutput(collection=[])
+
+
# Importing these must happen after test invocations are defined or they won't register
from invokeai.app.services.events.events_base import EventServiceBase # noqa: E402
from invokeai.app.services.shared.graph import Edge, EdgeConnection, GraphExecutionState # noqa: E402