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
fix: infer If output types from branches
JPPhoto49ea3fb87a22
diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.pyindex 36bcba1bc7..9ee119752d 100644--- a/invokeai/app/services/shared/graph_validation.py+++ b/invokeai/app/services/shared/graph_validation.py@@ -757,9 +757,61 @@ class Graph(BaseModel):if edge not in self.edges:list.append(self.edges, edge)self._add_edge_to_indexes(edge)+ try:+ self._validate_if_branch_input_dependents(edge)+ except Exception:+ self.delete_edge(edge)+ raiseelse:raise InvalidEdgeError()+ def _validate_if_branch_input_dependents(self, edge: Edge) -> None:+ """Revalidate downstream edges when adding an If branch makes its output type more specific."""+ node = self.get_node(edge.destination.node_id)+ if not isinstance(node, IfInvocation) or edge.destination.field not in ("true_input", "false_input"):+ return++ pending_node_ids = [node.id]+ validated_node_ids: set[str] = set()+ while pending_node_ids:+ node_id = pending_node_ids.pop()+ if node_id in validated_node_ids:+ continue+ validated_node_ids.add(node_id)++ if self._get_effective_output_connections(node_id, "value") is None:+ continue++ for output_edge in self._get_output_edges(node_id, "value"):+ destination_node = self.get_node(output_edge.destination.node_id)+ self._validate_edge_field_compatibility(output_edge, destination_node)++ if (+ isinstance(destination_node, IterateInvocation)+ and output_edge.destination.field == COLLECTION_FIELD+ ):+ err = self._is_iterator_connection_valid(destination_node.id)+ if err is not None:+ raise InvalidEdgeError(+ f"Iterator input type does not match iterator output type ({output_edge}): {err}"+ )++ if isinstance(destination_node, CollectInvocation) and output_edge.destination.field in (+ ITEM_FIELD,+ COLLECTION_FIELD,+ ):+ err = self._is_collector_connection_valid(destination_node.id)+ if err is not None:+ raise InvalidEdgeError(+ f"Collector output type does not match collector input type ({output_edge}): {err}"+ )++ if isinstance(destination_node, IfInvocation) and output_edge.destination.field in (+ "true_input",+ "false_input",+ ):+ pending_node_ids.append(destination_node.id)+def _extend_edges_unchecked(self, edges: Iterable[Edge]) -> None:"""Adds trusted runtime edges without author-time graph validation.@@ -831,11 +883,8 @@ class Graph(BaseModel):):continueself._validate_edge_not_to_direct_input(edge, destination_node)- if not are_connections_compatible(- self.get_node(edge.source.node_id),- edge.source.field,- destination_node,- edge.destination.field,+ if not self._are_effective_connections_compatible(+ edge.source.node_id, edge.source.field, destination_node, edge.destination.field):raise InvalidEdgeError(f"Edge source and target types do not match ({edge})")@@ -956,15 +1005,15 @@ class Graph(BaseModel):if not nx.is_directed_acyclic_graph(graph):raise InvalidEdgeError(f"Edge creates a cycle in the graph ({edge})")- def _validate_edge_field_compatibility(- self, edge: Edge, source_node: BaseInvocation, destination_node: BaseInvocation- ) -> None:+ def _validate_edge_field_compatibility(self, edge: Edge, destination_node: BaseInvocation) -> None:if isinstance(destination_node, CallSavedWorkflowInvocation) and is_call_saved_workflow_dynamic_input(edge.destination.field):returnself._validate_edge_not_to_direct_input(edge, destination_node)- if not are_connections_compatible(source_node, edge.source.field, destination_node, edge.destination.field):+ if not self._are_effective_connections_compatible(+ edge.source.node_id, edge.source.field, destination_node, edge.destination.field+ ):raise InvalidEdgeError(f"Field types are incompatible ({edge})")def _validate_edge_not_to_direct_input(self, edge: Edge, destination_node: BaseInvocation) -> None:@@ -1048,7 +1097,7 @@ class Graph(BaseModel):returnself._validate_edge_destination_uniqueness(edge, destination_node)self._validate_edge_would_not_create_cycle(edge)- self._validate_edge_field_compatibility(edge, source_node, destination_node)+ self._validate_edge_field_compatibility(edge, destination_node)self._validate_iterator_edge_rules(edge, source_node, destination_node)self._validate_collector_edge_rules(edge, source_node, destination_node, allow_inputless_source_collector)@@ -1826,16 +1875,22 @@ class Graph(BaseModel):return presence_errorinput_node = self.get_node(inputs[0].node_id)- input_field_type = get_output_field_type(input_node, inputs[0].field)+ input_sources = self._get_effective_output_connections(inputs[0].node_id, inputs[0].field)+ input_field_types = (+ [get_output_field_type(self.get_node(source.node_id), source.field) for source in input_sources]+ if input_sources is not None+ else [get_output_field_type(input_node, inputs[0].field)]+ )output_field_types = self._get_iterator_output_field_types(outputs)- input_type_error = self._validate_iterator_input_type(input_field_type)- if input_type_error is not None:- return input_type_error+ for input_field_type in input_field_types:+ input_type_error = self._validate_iterator_input_type(input_field_type)+ if input_type_error is not None:+ return input_type_error- output_type_error = self._validate_iterator_output_types(input_field_type, output_field_types)- if output_type_error is not None:- return output_type_error+ output_type_error = self._validate_iterator_output_types(input_field_type, output_field_types)+ if output_type_error is not None:+ return output_type_errorreturn self._validate_iterator_collector_input(input_node, output_field_types)@@ -1873,6 +1928,63 @@ class Graph(BaseModel):return "Iterator collection type must match all iterator output types"return None+ def _get_effective_output_connections(+ self, node_id: str, field: str, visited: Optional[set[tuple[str, str]]] = None+ ) -> list[EdgeConnection] | None:+ """Resolve an If output to its connected branch sources, or None when a branch is unresolved."""+ if visited is None:+ visited = set()+ source = (node_id, field)+ node = self.get_node(node_id)+ if not isinstance(node, IfInvocation) or field != "value":+ return [EdgeConnection(node_id=node_id, field=field)]+ if source in visited:+ return None+ visited.add(source)++ sources: list[EdgeConnection] = []+ for branch_field in ("true_input", "false_input"):+ branch_edges = self._get_input_edges(node_id, branch_field)+ if len(branch_edges) != 1:+ return None++ branch_edge = branch_edges[0]+ branch_sources = self._get_effective_output_connections(+ branch_edge.source.node_id, branch_edge.source.field, visited.copy()+ )+ if branch_sources is None:+ return None+ sources.extend(branch_sources)++ return sources++ def _get_effective_output_field_types(self, node_id: str, field: str) -> set[Any]:+ sources = self._get_effective_output_connections(node_id, field)+ if sources is None:+ return {Any}++ source_types = {get_output_field_type(self.get_node(source.node_id), source.field) for source in sources}+ if not source_types or any(is_any(source_type) for source_type in source_types):+ return {Any}+ return source_types++ def _are_effective_connections_compatible(+ self,+ source_node_id: str,+ source_field: str,+ destination_node: BaseInvocation,+ destination_field: str,+ ) -> bool:+ """Checks each known branch of an If output against a target while preserving compatibility hooks."""+ sources = self._get_effective_output_connections(source_node_id, source_field)+ if sources is None:+ source_node = self.get_node(source_node_id)+ return are_connections_compatible(source_node, source_field, destination_node, destination_field)+ return all(+ are_connections_compatible(self.get_node(source.node_id), source.field, destination_node, destination_field)+ for source in sources+ )+def _resolve_collector_input_types(self, node_id: str, visited: Optional[set[str]] = None) -> set[Any]:"""Resolves possible item types for a collector's inputs, recursively following chained collectors."""visited = visited or set()@@ -1883,9 +1995,8 @@ class Graph(BaseModel):input_types: set[Any] = set()for edge in self._get_input_edges(node_id, ITEM_FIELD):- input_field_type = get_output_field_type(self.get_node(edge.source.node_id), edge.source.field)- resolved_types = [input_field_type] if get_origin(input_field_type) is None else get_args(input_field_type)- input_types.update(t for t in resolved_types if t != NoneType)+ input_field_types = list(self._get_effective_output_field_types(edge.source.node_id, edge.source.field))+ input_types.update(self._resolve_item_input_types(input_field_types))for edge in self._get_input_edges(node_id, COLLECTION_FIELD):source_node = self.get_node(edge.source.node_id)@@ -1893,8 +2004,8 @@ class Graph(BaseModel):input_types.update(self._resolve_collector_input_types(source_node.id, visited.copy()))continue- input_field_type = get_output_field_type(source_node, edge.source.field)- input_types.update(extract_collection_item_types(input_field_type))+ for input_field_type in self._get_effective_output_field_types(edge.source.node_id, edge.source.field):+ input_types.update(extract_collection_item_types(input_field_type))return input_types@@ -1947,9 +2058,15 @@ class Graph(BaseModel):collection_inputs: list[EdgeConnection],outputs: list[EdgeConnection],) -> tuple[list[Any], list[Any], list[Any]]:- item_input_field_types = [get_output_field_type(self.get_node(e.node_id), e.field) for e in item_inputs]+ item_input_field_types = [+ field_type+ for edge in item_inputs+ for field_type in self._get_effective_output_field_types(edge.node_id, edge.field)+ ]collection_input_field_types = [- get_output_field_type(self.get_node(e.node_id), e.field) for e in collection_inputs+ field_type+ for edge in collection_inputs+ for field_type in self._get_effective_output_field_types(edge.node_id, edge.field)]output_field_types = [get_input_field_type(self.get_node(e.node_id), e.field) for e in outputs]return item_input_field_types, collection_input_field_types, output_field_types@@ -1964,16 +2081,15 @@ class Graph(BaseModel):if resolved_type != NoneType}- def _resolve_collection_input_types(- self, collection_inputs: list[EdgeConnection], collection_input_field_types: list[Any]- ) -> set[Any]:+ def _resolve_collection_input_types(self, collection_inputs: list[EdgeConnection]) -> set[Any]:input_field_types: set[Any] = set()- for input_conn, input_field_type in zip(collection_inputs, collection_input_field_types, strict=False):+ for input_conn in collection_inputs:source_node = self.get_node(input_conn.node_id)if isinstance(source_node, CollectInvocation) and input_conn.field == COLLECTION_FIELD:input_field_types.update(self._resolve_collector_input_types(source_node.id))continue- input_field_types.update(extract_collection_item_types(input_field_type))+ for input_field_type in self._get_effective_output_field_types(input_conn.node_id, input_conn.field):+ input_field_types.update(extract_collection_item_types(input_field_type))return input_field_typesdef _validate_collector_collection_inputs(self, collection_input_field_types: list[Any]) -> str | None:@@ -2050,7 +2166,7 @@ class Graph(BaseModel):return collection_input_errorinput_field_types = self._resolve_item_input_types(item_input_field_types)- input_field_types.update(self._resolve_collection_input_types(collection_inputs, collection_input_field_types))+ input_field_types.update(self._resolve_collection_input_types(collection_inputs))has_multiple_root_types, input_root_type = self._get_collector_input_root_type_from_resolved_types(input_field_typesdiff --git a/tests/test_node_graph.py b/tests/test_node_graph.pyindex f780550772..d1e98def52 100644--- a/tests/test_node_graph.py+++ b/tests/test_node_graph.py@@ -18,6 +18,7 @@ from invokeai.app.invocations.baseinvocation import (invocation_output,)from invokeai.app.invocations.fields import InputField, OutputField, OutputScope+from invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.invocations.loops import ForInvocation, ForReturnInvocationfrom invokeai.app.invocations.math import AddInvocationfrom invokeai.app.invocations.primitives import (@@ -1064,6 +1065,129 @@ def test_graph_connects_collector():g.add_edge(e3)+def test_graph_collector_accepts_if_output_when_both_branches_have_matching_type():+ graph = Graph()+ true_value = StringInvocation(id="true", value="true")+ false_value = StringInvocation(id="false", value="false")+ if_node = IfInvocation(id="if")+ collector = CollectInvocation(id="collect")+ consumer = PromptCollectionTestInvocation(id="consumer", collection=[])+ for node in (true_value, false_value, if_node, collector, consumer):+ graph.add_node(node)++ graph.add_edge(create_edge(true_value.id, "value", if_node.id, "true_input"))+ graph.add_edge(create_edge(false_value.id, "value", if_node.id, "false_input"))+ graph.add_edge(create_edge(if_node.id, "value", collector.id, "item"))+ graph.add_edge(create_edge(collector.id, "collection", consumer.id, "collection"))+++def test_graph_collectors_accept_if_output_with_and_without_a_string_collection_seed():+ graph = Graph()+ true_value = StringInvocation(id="true", value="true")+ false_value = StringInvocation(id="false", value="false")+ if_node = IfInvocation(id="if")+ unseeded_collector = CollectInvocation(id="unseeded_collect")+ seeded_collector = CollectInvocation(id="seeded_collect")+ seed = StringCollectionInvocation(id="seed", collection=["existing"])+ unseeded_consumer = PromptCollectionTestInvocation(id="unseeded_consumer", collection=[])+ seeded_consumer = PromptCollectionTestInvocation(id="seeded_consumer", collection=[])+ for node in (+ true_value,+ false_value,+ if_node,+ unseeded_collector,+ seeded_collector,+ seed,+ unseeded_consumer,+ seeded_consumer,+ ):+ graph.add_node(node)++ graph.add_edge(create_edge(true_value.id, "value", if_node.id, "true_input"))+ graph.add_edge(create_edge(false_value.id, "value", if_node.id, "false_input"))+ graph.add_edge(create_edge(if_node.id, "value", unseeded_collector.id, "item"))+ graph.add_edge(create_edge(if_node.id, "value", seeded_collector.id, "item"))+ graph.add_edge(create_edge(seed.id, "collection", seeded_collector.id, "collection"))+ graph.add_edge(create_edge(unseeded_collector.id, "collection", unseeded_consumer.id, "collection"))+ graph.add_edge(create_edge(seeded_collector.id, "collection", seeded_consumer.id, "collection"))+++def test_graph_rejects_if_output_when_its_branches_do_not_match_target_type():+ graph = Graph()+ true_value = StringInvocation(id="true", value="true")+ false_value = StringInvocation(id="false", value="false")+ if_node = IfInvocation(id="if")+ consumer = ImageToImageTestInvocation(id="consumer")+ for node in (true_value, false_value, if_node, consumer):+ graph.add_node(node)++ graph.add_edge(create_edge(true_value.id, "value", if_node.id, "true_input"))+ graph.add_edge(create_edge(false_value.id, "value", if_node.id, "false_input"))++ with pytest.raises(InvalidEdgeError, match="Field types are incompatible"):+ graph.add_edge(create_edge(if_node.id, "value", consumer.id, "image"))+++def test_graph_rejects_if_branch_that_invalidates_existing_output_edge():+ graph = Graph()+ true_value = StringInvocation(id="true", value="true")+ false_value = IntegerInvocation(id="false", value=1)+ if_node = IfInvocation(id="if")+ consumer = ImageToImageTestInvocation(id="consumer")+ for node in (true_value, false_value, if_node, consumer):+ graph.add_node(node)++ graph.add_edge(create_edge(true_value.id, "value", if_node.id, "true_input"))+ graph.add_edge(create_edge(if_node.id, "value", consumer.id, "image"))++ false_branch_edge = create_edge(false_value.id, "value", if_node.id, "false_input")+ with pytest.raises(InvalidEdgeError):+ graph.add_edge(false_branch_edge)++ assert false_branch_edge not in graph.edges+ assert graph.is_valid()+++def test_graph_rejects_if_branch_that_makes_collector_items_incompatible():+ graph = Graph()+ true_value = StringInvocation(id="true", value="true")+ false_value = IntegerInvocation(id="false", value=1)+ if_node = IfInvocation(id="if")+ collector = CollectInvocation(id="collect")+ seed = StringCollectionInvocation(id="seed", collection=["existing"])+ consumer = PromptCollectionTestInvocation(id="consumer", collection=[])+ for node in (true_value, false_value, if_node, collector, seed, consumer):+ graph.add_node(node)++ graph.add_edge(create_edge(true_value.id, "value", if_node.id, "true_input"))+ graph.add_edge(create_edge(if_node.id, "value", collector.id, "item"))+ graph.add_edge(create_edge(seed.id, "collection", collector.id, "collection"))+ graph.add_edge(create_edge(collector.id, "collection", consumer.id, "collection"))++ false_branch_edge = create_edge(false_value.id, "value", if_node.id, "false_input")+ with pytest.raises(InvalidEdgeError, match="Collector output type does not match collector input type"):+ graph.add_edge(false_branch_edge)++ assert false_branch_edge not in graph.edges+ assert graph.is_valid()+++def test_graph_rejects_mixed_if_branch_types_for_collector_items():+ graph = Graph()+ string_value = StringInvocation(id="string", value="text")+ integer_value = IntegerInvocation(id="integer", value=1)+ if_node = IfInvocation(id="if")+ collector = CollectInvocation(id="collect")+ for node in (string_value, integer_value, if_node, collector):+ graph.add_node(node)++ graph.add_edge(create_edge(string_value.id, "value", if_node.id, "true_input"))+ graph.add_edge(create_edge(integer_value.id, "value", if_node.id, "false_input"))++ with pytest.raises(InvalidEdgeError, match="Collector input collection items must be of a single type"):+ graph.add_edge(create_edge(if_node.id, "value", collector.id, "item"))++def test_graph_rejects_collector_output_edge_before_input_edge():graph = Graph()graph.add_node(CollectInvocation(id="collect"))