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 collector scoping and invocation validation (#9483)

Jonathanccd5896cafd1
diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.py
index 1c1a35d700..351e22a88d 100644
--- a/invokeai/app/invocations/baseinvocation.py
+++ b/invokeai/app/invocations/baseinvocation.py
@@ -774,8 +774,10 @@ def invocation(
if isinstance(invoke_return_annotation, str):
invoke_return_annotation = getattr(sys.modules[cls.__module__], invoke_return_annotation)
- assert invoke_return_annotation is not BaseInvocationOutput
- assert issubclass(invoke_return_annotation, BaseInvocationOutput)
+ if invoke_return_annotation is BaseInvocationOutput or not issubclass(
+ invoke_return_annotation, BaseInvocationOutput
+ ):
+ raise TypeError
except Exception:
raise ValueError(
f'Invocation "{invocation_type}" must have a return annotation of a subclass of BaseInvocationOutput (got "{invoke_return_annotation}")'
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index fc48a5af8b..1d233e028a 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -514,36 +514,59 @@ class _ExecutionMaterializer:
self._state._try_resolve_if_node(exec_node_id)
self._state._enqueue_if_ready(exec_node_id)
- def _get_collect_iteration_group_key(self, edge: Edge) -> tuple[int, ...]:
+ def _get_collect_iteration_group_key(self, edge: Edge, sibling_depth: Optional[int] = None) -> tuple[int, ...]:
path = self._state._get_iteration_path(edge.source.node_id)
if edge.destination.field == ITEM_FIELD:
- return path[:-1]
+ # Ragged siblings need the deepest path to identify their shared outer group.
+ depth = len(path) if sibling_depth is None else sibling_depth
+ return path[: max(depth - 1, 0)]
return path
+ def _get_collect_source_iterator_ids(self, source_node_id: str) -> list[str]:
+ iterator_node_ids = self.get_node_iterators(source_node_id)
+ if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
+ iterator_node_ids.append(source_node_id)
+ return iterator_node_ids
+
def _get_ordered_prepared_nodes_for_source(self, source_node_id: str) -> list[str]:
return sorted(
self._get_prepared_nodes_for_source(source_node_id),
key=lambda exec_node_id: (self._state._get_iteration_path(exec_node_id), exec_node_id),
)
+ def _get_iterator_input_iteration_paths(self, iterator_node_id: str) -> set[tuple[int, ...]]:
+ iteration_paths: set[tuple[int, ...]] = set()
+ for edge in self._state.graph._get_input_edges(iterator_node_id, COLLECTION_FIELD):
+ source_node_id = edge.source.node_id
+ prepared_nodes = self._get_ordered_prepared_nodes_for_source(source_node_id)
+ iteration_paths.update(self._state._get_iteration_path(prepared_id) for prepared_id in prepared_nodes)
+ return iteration_paths
+
def _get_collect_candidate_group_keys(self, edge: Edge) -> set[tuple[int, ...]]:
source_node_id = edge.source.node_id
- iterator_node_ids = self.get_node_iterators(source_node_id)
- if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
- iterator_node_ids.append(source_node_id)
+ iterator_node_ids = self._get_collect_source_iterator_ids(source_node_id)
group_depth = len(iterator_node_ids)
if edge.destination.field == ITEM_FIELD:
group_depth = max(group_depth - 1, 0)
+
+ group_keys: set[tuple[int, ...]] = set()
+ for iterator_node_id in iterator_node_ids:
+ prepared_nodes = self._get_ordered_prepared_nodes_for_source(iterator_node_id)
+ # Prepared paths use the active group depth. Input paths stay full to preserve scope across collectors.
+ if prepared_nodes and group_depth:
+ group_keys.update(
+ iteration_path[:group_depth]
+ for prepared_id in prepared_nodes
+ if len(iteration_path := self._state._get_iteration_path(prepared_id)) >= group_depth
+ )
+ group_keys.update(self._get_iterator_input_iteration_paths(iterator_node_id))
+
+ if group_keys:
+ return group_keys
if group_depth == 0:
return {()}
-
- return {
- iteration_path[:group_depth]
- for iterator_node_id in iterator_node_ids
- for prepared_id in self._get_ordered_prepared_nodes_for_source(iterator_node_id)
- if len(iteration_path := self._state._get_iteration_path(prepared_id)) >= group_depth
- }
+ return set()
def _get_collect_iteration_mapping_groups(
self, input_edges: list[Edge]
@@ -553,12 +576,15 @@ class _ExecutionMaterializer:
for edge in input_edges:
group_keys.update(self._get_collect_candidate_group_keys(edge))
prepared_nodes = self._get_ordered_prepared_nodes_for_source(edge.source.node_id)
+ sibling_depth = max(
+ (len(self._state._get_iteration_path(prepared_id)) for prepared_id in prepared_nodes), default=0
+ )
for prepared_id in prepared_nodes:
prepared_edge = Edge(
source=EdgeConnection(node_id=prepared_id, field=edge.source.field),
destination=edge.destination,
)
- group_key = self._get_collect_iteration_group_key(prepared_edge)
+ group_key = self._get_collect_iteration_group_key(prepared_edge, sibling_depth)
group_keys.add(group_key)
prepared_inputs.append(
(prepared_edge, edge.source.node_id, prepared_id, self._state._get_iteration_path(prepared_id))
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index 5242b54e9c..a65b169c2a 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -50,6 +50,15 @@ class IntegerCollectionFromItemTestInvocation(BaseInvocation):
return IntegerCollectionTestInvocationOutput(collection=[base, base + 1])
+class IntegerCollectionWithBranchingTestInvocation(BaseInvocation):
+ value: int = InputField(default=0)
+ branch_count: int = InputField(default=2)
+
+ def invoke(self, context: InvocationContext) -> IntegerCollectionTestInvocationOutput:
+ base = self.value * 10
+ return IntegerCollectionTestInvocationOutput(collection=[base + branch for branch in range(self.branch_count)])
+
+
class MaybeEmptyIntegerCollectionTestInvocation(BaseInvocation):
value: int = InputField(default=0)
always_empty: bool = InputField(default=False)
@@ -60,6 +69,13 @@ class MaybeEmptyIntegerCollectionTestInvocation(BaseInvocation):
return IntegerCollectionTestInvocationOutput(collection=[self.value])
+class EmptyOrTwoIntegerCollectionTestInvocation(BaseInvocation):
+ value: int = InputField(default=0)
+
+ def invoke(self, context: InvocationContext) -> IntegerCollectionTestInvocationOutput:
+ return IntegerCollectionTestInvocationOutput(collection=[] if self.value == 0 else [0, 1])
+
+
class IntegerCollectionPassthroughTestInvocation(BaseInvocation):
collection: list[int] = InputField(default=[])
@@ -75,6 +91,14 @@ class TwoIntegerCollectionsTestInvocation(BaseInvocation):
return IntegerCollectionTestInvocationOutput(collection=self.first + self.second)
+class IntegerAndCollectionTestInvocation(BaseInvocation):
+ value: int = InputField(default=0)
+ collection: list[int] = InputField(default=[])
+
+ def invoke(self, context: InvocationContext) -> IntegerCollectionTestInvocationOutput:
+ return IntegerCollectionTestInvocationOutput(collection=[self.value, *self.collection])
+
+
@pytest.fixture
def simple_graph() -> Graph:
g = Graph()
@@ -1249,6 +1273,161 @@ def test_graph_collector_nested_under_outer_iterator_preserves_empty_groups(
assert state.is_complete()
+def test_graph_consumer_with_direct_iterator_and_empty_collector_preserves_outer_iterations():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="outer_range", start=0, stop=2, step=1))
+ graph.add_node(IterateInvocation(id="outer_iter"))
+ graph.add_node(MaybeEmptyIntegerCollectionTestInvocation(id="inner_collection"))
+ graph.add_node(IterateInvocation(id="inner_iter"))
+ graph.add_node(AddInvocation(id="inner_item", b=0))
+ graph.add_node(CollectInvocation(id="inner_collect"))
+ graph.add_node(IntegerAndCollectionTestInvocation(id="join"))
+ graph.add_node(CollectInvocation(id="outer_collect"))
+
+ graph.add_edge(create_edge("outer_range", "collection", "outer_iter", "collection"))
+ graph.add_edge(create_edge("outer_iter", "item", "inner_collection", "value"))
+ graph.add_edge(create_edge("inner_collection", "collection", "inner_iter", "collection"))
+ graph.add_edge(create_edge("inner_iter", "item", "inner_item", "a"))
+ graph.add_edge(create_edge("inner_item", "value", "inner_collect", "item"))
+ graph.add_edge(create_edge("inner_collect", "collection", "join", "collection"))
+ graph.add_edge(create_edge("outer_iter", "item", "join", "value"))
+ graph.add_edge(create_edge("join", "collection", "outer_collect", "item"))
+
+ state = GraphExecutionState(graph=graph)
+ execute_all_nodes(state)
+
+ join_ids = state.source_prepared_mapping["join"]
+ assert sorted(state._get_iteration_path(node_id) for node_id in join_ids) == [(0,), (1,)]
+ assert sorted(state.results[node_id].collection for node_id in join_ids) == [[0], [1, 1]]
+ outer_collect_id = next(iter(state.source_prepared_mapping["outer_collect"]))
+ assert state.results[outer_collect_id].collection == [[0], [1, 1]]
+
+
+ ("always_empty", "expected"),
+ [(True, [[], []]), (False, [[0, 1], [10, 11]]), (None, [[], [1]])],
+)
+def test_graph_chained_collectors_preserve_outer_iteration_scope(always_empty: bool | None, expected: list[list[int]]):
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="outer_range", start=0, stop=2, step=1))
+ graph.add_node(IterateInvocation(id="outer_iter"))
+ if always_empty is not False:
+ graph.add_node(
+ MaybeEmptyIntegerCollectionTestInvocation(id="inner_collection", always_empty=always_empty is True)
+ )
+ else:
+ graph.add_node(IntegerCollectionFromItemTestInvocation(id="inner_collection"))
+ graph.add_node(IterateInvocation(id="inner_iter"))
+ graph.add_node(AddInvocation(id="inner_item", b=0))
+ graph.add_node(CollectInvocation(id="collect_a"))
+ graph.add_node(IterateInvocation(id="downstream_iter"))
+ graph.add_node(AddInvocation(id="downstream_body", b=0))
+ graph.add_node(CollectInvocation(id="collect_b"))
+ graph.add_node(IntegerCollectionPassthroughTestInvocation(id="per_outer"))
+ graph.add_node(CollectInvocation(id="outer_collect"))
+
+ graph.add_edge(create_edge("outer_range", "collection", "outer_iter", "collection"))
+ graph.add_edge(create_edge("outer_iter", "item", "inner_collection", "value"))
+ graph.add_edge(create_edge("inner_collection", "collection", "inner_iter", "collection"))
+ graph.add_edge(create_edge("inner_iter", "item", "inner_item", "a"))
+ graph.add_edge(create_edge("inner_item", "value", "collect_a", "item"))
+ graph.add_edge(create_edge("collect_a", "collection", "downstream_iter", "collection"))
+ graph.add_edge(create_edge("downstream_iter", "item", "downstream_body", "a"))
+ graph.add_edge(create_edge("downstream_body", "value", "collect_b", "item"))
+ graph.add_edge(create_edge("collect_b", "collection", "per_outer", "collection"))
+ graph.add_edge(create_edge("per_outer", "collection", "outer_collect", "item"))
+
+ state = GraphExecutionState(graph=graph)
+ execute_all_nodes(state)
+
+ collect_b_ids = state.source_prepared_mapping["collect_b"]
+ assert sorted(state._get_iteration_path(node_id) for node_id in collect_b_ids) == [(0,), (1,)]
+ assert sorted(state.results[node_id].collection for node_id in collect_b_ids) == expected
+ outer_collect_id = next(iter(state.source_prepared_mapping["outer_collect"]))
+ assert state.results[outer_collect_id].collection == expected
+
+
+def test_graph_chained_collectors_preserve_ragged_empty_scope():
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="source", start=0, stop=2, step=1))
+ graph.add_node(IterateInvocation(id="outer_iter"))
+ graph.add_node(EmptyOrTwoIntegerCollectionTestInvocation(id="middle_map"))
+ graph.add_node(IterateInvocation(id="middle_iter"))
+ graph.add_node(IntegerCollectionFromItemTestInvocation(id="inner_map"))
+ graph.add_node(IterateInvocation(id="inner_iter"))
+ graph.add_node(AddInvocation(id="body", b=0))
+ graph.add_node(CollectInvocation(id="collect_a"))
+ graph.add_node(IntegerCollectionPassthroughTestInvocation(id="per_x"))
+ graph.add_node(CollectInvocation(id="top_collect"))
+
+ graph.add_edge(create_edge("source", "collection", "outer_iter", "collection"))
+ graph.add_edge(create_edge("outer_iter", "item", "middle_map", "value"))
+ graph.add_edge(create_edge("middle_map", "collection", "middle_iter", "collection"))
+ graph.add_edge(create_edge("middle_iter", "item", "inner_map", "value"))
+ graph.add_edge(create_edge("inner_map", "collection", "inner_iter", "collection"))
+ graph.add_edge(create_edge("inner_iter", "item", "body", "a"))
+ graph.add_edge(create_edge("body", "value", "collect_a", "item"))
+ graph.add_edge(create_edge("collect_a", "collection", "per_x", "collection"))
+ graph.add_edge(create_edge("per_x", "collection", "top_collect", "item"))
+
+ state = GraphExecutionState(graph=graph)
+ execute_all_nodes(state)
+
+ top_collect_ids = state.source_prepared_mapping["top_collect"]
+ top_collect_results = {
+ state._get_iteration_path(node_id): state.results[node_id].collection for node_id in top_collect_ids
+ }
+ assert top_collect_results == {(0,): [[]], (1,): [[0, 1], [10, 11]]}
+
+
[email protected](("levels", "branch_count"), [(3, 2), (4, 2), (5, 1), (6, 1), (7, 1)])
+def test_graph_chained_collectors_preserve_all_iteration_scopes(levels: int, branch_count: int):
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="source", start=0, stop=2, step=1))
+ graph.add_node(IterateInvocation(id="iter_0"))
+ for level in range(1, levels):
+ graph.add_node(IntegerCollectionWithBranchingTestInvocation(id=f"map_{level}", branch_count=branch_count))
+ graph.add_node(IterateInvocation(id=f"iter_{level}"))
+ graph.add_node(AddInvocation(id="body", b=0))
+
+ graph.add_edge(create_edge("source", "collection", "iter_0", "collection"))
+ for level in range(1, levels):
+ graph.add_edge(create_edge(f"iter_{level - 1}", "item", f"map_{level}", "value"))
+ graph.add_edge(create_edge(f"map_{level}", "collection", f"iter_{level}", "collection"))
+ graph.add_edge(create_edge(f"iter_{levels - 1}", "item", "body", "a"))
+
+ previous_node_id = "body"
+ previous_field = "value"
+ for level in reversed(range(levels)):
+ collect_id = f"collect_{level}"
+ graph.add_node(CollectInvocation(id=collect_id))
+ graph.add_edge(create_edge(previous_node_id, previous_field, collect_id, "item"))
+ previous_node_id = collect_id
+ previous_field = "collection"
+
+ state = GraphExecutionState(graph=graph)
+ execute_all_nodes(state)
+
+ def paths(depth: int) -> list[tuple[int, ...]]:
+ if depth == 0:
+ return [()]
+ branch_level = depth - 1
+ branch_options = range(2) if branch_level == 0 else range(branch_count)
+ return [prefix + (branch,) for prefix in paths(depth - 1) for branch in branch_options]
+
+ def expected_collection(level: int, prefix: tuple[int, ...]):
+ branch_options = range(2) if level == 0 else range(branch_count)
+ if level == levels - 1:
+ return [int("".join(map(str, prefix + (branch,)))) for branch in branch_options]
+ return [expected_collection(level + 1, prefix + (branch,)) for branch in branch_options]
+
+ for level in range(levels):
+ prepared_ids = state.source_prepared_mapping[f"collect_{level}"]
+ actual = {state._get_iteration_path(node_id): state.results[node_id].collection for node_id in prepared_ids}
+ expected = {prefix: expected_collection(level, prefix) for prefix in paths(level)}
+ assert actual == expected
+
+
def test_graph_collector_reuses_outer_collection_input_for_each_nested_iterator_group():
graph = Graph()
diff --git a/tests/test_node_graph.py b/tests/test_node_graph.py
index 64e652a61d..93e198b376 100644
--- a/tests/test_node_graph.py
+++ b/tests/test_node_graph.py
@@ -1,5 +1,9 @@
import copy
import pickle
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
import pytest
from pydantic import TypeAdapter, ValidationError
@@ -988,6 +992,36 @@ def test_nodes_must_return_invocation_output():
return "foo"
+def test_nodes_must_return_invocation_output_under_optimized_python():
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-O",
+ "-c",
+ textwrap.dedent(
+ """
+ from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
+
+ try:
+ @invocation("test_no_output_optimized", version="1.0.0")
+ class NoOutputInvocation(BaseInvocation):
+ def invoke(self) -> str:
+ return "foo"
+ except ValueError:
+ pass
+ else:
+ raise SystemExit("invalid invocation return annotation was accepted under python -O")
+ """
+ ),
+ ],
+ capture_output=True,
+ cwd=Path(__file__).resolve().parents[1],
+ text=True,
+ )
+
+ assert result.returncode == 0, result.stderr or result.stdout
+
+
def test_collector_different_incomers():
"""Tests an edge case where a collector has incoming edges from invocations with differently-named output fields."""
g = Graph()