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(graph): preserve numeric collector inputs
JPPhotob62a32aa536f
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex c770ad46b8..f05a893868 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -207,8 +207,10 @@ Runs a sequence of checks:hooks; the current condition value does not narrow the possible types.- Collector item/collection checks and iterator collection checks also use the resolved branch sources. This allowsmatching string branches to feed a string collector without an intermediate string node.- - If a branch is unresolved or traversal encounters a cycle, retain the declared output compatibility behavior- (`Any` for collector type inference). The graph's separate DAG check still rejects cycles.+ - If a branch is unresolved, retain the declared output compatibility behavior (`Any` for collector type+ inference). The graph's separate DAG check rejects cycles before projection.+ - Collectors can combine `int` and `float` items as `float`, preserving numeric workflows whose downstream+ consumers accept floats; unrelated mixed item types remain invalid.- Ordinary source ports use the direct compatibility path with already resolved nodes, without If traversal orprojection allocations.diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.pyindex fc335e7f58..c819b56451 100644--- a/invokeai/app/services/shared/graph_validation.py+++ b/invokeai/app/services/shared/graph_validation.py@@ -1948,31 +1948,22 @@ class Graph(BaseModel):return Nonedef _get_effective_output_connections(self, node_id: str, field: str) -> list[EdgeConnection] | None:- """Resolve an If output to its unique branch sources, or None when a branch is unresolved or cyclic."""- root_source = (node_id, field)- root_node = self.get_node(node_id)- if not isinstance(root_node, IfInvocation) or field != "value":- return [EdgeConnection(node_id=node_id, field=field)]-- pending: list[tuple[str, str, bool]] = [(node_id, field, False)]- active: set[tuple[str, str]] = set()+ """Resolve If.value to its unique branch sources, or None when a branch is unresolved.++ Callers validate acyclicity before resolving connections.+ """+ pending = [(node_id, field)]visited: set[tuple[str, str]] = set()sources: list[EdgeConnection] = []while pending:- source_node_id, source_field, exiting = pending.pop()+ source_node_id, source_field = pending.pop()source = (source_node_id, source_field)- if exiting:- active.remove(source)- visited.add(source)- continue- if source in active:- return Noneif source in visited:continue+ visited.add(source)- node = root_node if source == root_source else self.get_node(source_node_id)+ node = self.get_node(source_node_id)if not isinstance(node, IfInvocation) or source_field != "value":- visited.add(source)sources.append(EdgeConnection(node_id=source_node_id, field=source_field))continue@@ -1984,13 +1975,15 @@ class Graph(BaseModel):branch_edge = branch_edges[0]branch_sources.append((branch_edge.source.node_id, branch_edge.source.field))- active.add(source)- pending.append((source_node_id, source_field, True))- pending.extend((*branch_source, False) for branch_source in reversed(branch_sources))+ pending.extend(reversed(branch_sources))return sourcesdef _get_effective_output_field_types(self, node_id: str, field: str) -> set[Any]:+ node = self.get_node(node_id)+ if not isinstance(node, IfInvocation) or field != "value":+ return {get_output_field_type(node, field)}+sources = self._get_effective_output_connections(node_id, field)if sources is None:return {Any}@@ -2134,6 +2127,9 @@ class Graph(BaseModel):self, input_field_types: set[Any]) -> tuple[bool, Any | None]:non_any_input_field_types = {t for t in input_field_types if t != Any}+ if non_any_input_field_types == {int, float}:+ return False, float+root_types = self._get_type_tree_root_types(non_any_input_field_types)if len(root_types) > 1:return True, Nonediff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.pyindex 9753981475..36179cd771 100644--- a/tests/test_graph_execution_state.py+++ b/tests/test_graph_execution_state.py@@ -40,6 +40,7 @@ from invokeai.app.invocations.primitives import (BooleanInvocation,BooleanOutput,IntegerCollectionInvocation,+ StringCollectionInvocation,)from invokeai.app.invocations.workflow_return import WorkflowReturnOutputfrom invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache@@ -5064,6 +5065,37 @@ def test_if_invocation_output_connects_to_downstream_input():assert g.results[prepared_prompt_node_id].prompt == "connected value"+ ("condition", "selected_node_id", "unselected_node_id", "expected_values"),+ [+ (True, "true_values", "false_values", ["true-a", "true-b"]),+ (False, "false_values", "true_values", ["false-a"]),+ ],+)+def test_if_output_iterates_only_selected_collection_branch(+ condition: bool, selected_node_id: str, unselected_node_id: str, expected_values: list[str]+):+ graph = Graph()+ graph.add_node(StringCollectionInvocation(id="true_values", collection=["true-a", "true-b"]))+ graph.add_node(StringCollectionInvocation(id="false_values", collection=["false-a"]))+ graph.add_node(IfInvocation(id="if", condition=condition))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("true_values", "collection", "if", "true_input"))+ graph.add_edge(create_edge("false_values", "collection", "if", "false_input"))+ graph.add_edge(create_edge("if", "value", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "collect", "item"))++ state = GraphExecutionState(graph=graph)+ executed_node_ids = execute_all_nodes(state)++ collect_exec_ids = state.source_prepared_mapping["collect"]+ assert len(collect_exec_ids) == 1+ assert state.results[next(iter(collect_exec_ids))].collection == expected_values+ assert selected_node_id in executed_node_ids+ assert unselected_node_id not in executed_node_ids++@pytest.mark.xfail(strict=True, reason="Legacy eager If-node execution should no longer occur")def test_if_graph_current_behavior_executes_both_branches_and_shared_ancestors():graph = Graph()diff --git a/tests/test_node_graph.py b/tests/test_node_graph.pyindex b13a507657..ede560ddce 100644--- a/tests/test_node_graph.py+++ b/tests/test_node_graph.py@@ -1081,6 +1081,21 @@ def test_graph_collector_accepts_if_output_when_both_branches_have_matching_typegraph.add_edge(create_edge(collector.id, "collection", consumer.id, "collection"))+def test_graph_effective_if_output_deduplicates_shared_branch_sources():+ graph = Graph(+ nodes={+ "value": StringInvocation(id="value", value="shared"),+ "if": IfInvocation(id="if"),+ },+ edges=[+ create_edge("value", "value", "if", "true_input"),+ create_edge("value", "value", "if", "false_input"),+ ],+ )++ assert graph._get_effective_output_connections("if", "value") == [EdgeConnection(node_id="value", field="value")]++def test_graph_collectors_accept_if_output_with_and_without_a_string_collection_seed():graph = Graph()true_value = StringInvocation(id="true", value="true")@@ -1188,6 +1203,32 @@ def test_graph_rejects_mixed_if_branch_types_for_collector_items():graph.add_edge(create_edge(if_node.id, "value", collector.id, "item"))[email protected]("condition", [True, False])+def test_graph_accepts_and_runs_mixed_numeric_if_branches_through_iterator(condition: bool):+ graph = Graph()+ integer_value = IntegerInvocation(id="integer", value=2)+ float_value = FloatInvocation(id="float", value=3.5)+ if_node = IfInvocation(id="if", condition=condition)+ collector = CollectInvocation(id="collect")+ iterator = IterateInvocation(id="iterate")+ float_consumer = FloatInvocation(id="float_consumer")+ for node in (integer_value, float_value, if_node, collector, iterator, float_consumer):+ graph.add_node(node)++ graph.add_edge(create_edge(integer_value.id, "value", if_node.id, "true_input"))+ graph.add_edge(create_edge(float_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", iterator.id, "collection"))+ graph.add_edge(create_edge(iterator.id, "item", float_consumer.id, "value"))++ session = GraphExecutionState(graph=graph)+ run_session_with_mock_context(session)+ output = get_single_output_from_session(session, float_consumer.id)++ assert output.value == (2.0 if condition else 3.5)+ assert isinstance(output.value, float)++def test_graph_rejects_iterator_consumers_incompatible_with_if_collector_branches():graph = Graph()string_value = StringInvocation(id="string", value="text")@@ -1285,39 +1326,34 @@ def test_graph_if_branch_revalidates_only_affected_iterators_once(monkeypatch: passert validated_iterators == ["affected_iterator"][email protected]("operation", ["add_edge", "validate_self"])-def test_graph_ordinary_edge_validation_avoids_projection_work(operation: str, monkeypatch: pytest.MonkeyPatch):- nodes = [StringInvocation(id=f"string_{index}", value="text") for index in range(25)]- edges = [- create_edge(source.id, "value", target.id, "value") for source, target in zip(nodes, nodes[1:], strict=False)- ]- graph = Graph(nodes={node.id: node for node in nodes}, edges=edges if operation == "validate_self" else [])- node_lookups = 0- connection_allocations = 0- original_get_node = Graph.get_node+def test_graph_collector_validation_avoids_ordinary_source_allocations(monkeypatch: pytest.MonkeyPatch):+ item_sources = [StringInvocation(id=f"string_{index}", value="text") for index in range(16)]+ seed = StringCollectionInvocation(id="seed", collection=["seed"])+ collector = CollectInvocation(id="collect")+ consumer = PromptCollectionTestInvocation(id="consumer", collection=[])+ nodes = [*item_sources, seed, collector, consumer]+ edges = [create_edge(source.id, "value", collector.id, "item") for source in item_sources]+ edges.extend(+ [+ create_edge(seed.id, "collection", collector.id, "collection"),+ create_edge(collector.id, "collection", consumer.id, "collection"),+ ]+ )+ graph = Graph(nodes={node.id: node for node in nodes}, edges=edges)original_connection_init = EdgeConnection.__init__-- def count_node_lookups(graph: Graph, node_id: str):- nonlocal node_lookups- node_lookups += 1- return original_get_node(graph, node_id)+ connection_allocations = 0def count_connection_allocations(connection: EdgeConnection, **kwargs: Any):nonlocal connection_allocationsconnection_allocations += 1original_connection_init(connection, **kwargs)- monkeypatch.setattr(Graph, "get_node", count_node_lookups)monkeypatch.setattr(EdgeConnection, "__init__", count_connection_allocations)- if operation == "add_edge":- for edge in edges:- graph.add_edge(edge)- else:- graph.validate_self()+ graph.validate_self()assert graph.edges == edges- assert (node_lookups, connection_allocations) == (2 * len(edges), 0)+ assert connection_allocations == 0def test_graph_validation_bounds_shared_if_branch_validation_work(monkeypatch: pytest.MonkeyPatch):