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): revalidate collector dependents on input changes
JPPhotob5d90800ceb6
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 249343db42..4a76664d03 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -205,8 +205,10 @@ Runs a sequence of checks:- For `IfInvocation.value`, resolve both branch inputs to their source ports, following nested `If` outputs anddeduplicating shared sources. Check every resolved source against the destination using the existing compatibilityhooks; 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 allows- matching string branches to feed a string collector without an intermediate string node.+ - Collector item/collection checks and iterator collection checks also use the resolved branch sources. When a+ branch source is a collector, use its inferred item root type instead of its declared `list[Any]` output. This+ preserves type checks through If branches and chained collectors, while matching string branches can feed a+ string collector without an intermediate string node.- Iterators over collectors validate their item consumers against the same inferred collector root type. Mixed`int` and `float` items therefore require consumers compatible with `float`.- If a branch is unresolved, retain the declared output compatibility behavior (`Any` for collector type@@ -244,10 +246,12 @@ Checks a single prospective edge before insertion:- Adding the edge to the flat DAG must keep it acyclic.- Iterator/collector constraints re-checked when the edge creates relevant patterns.-After inserting an edge into `If.true_input` or `If.false_input`, `add_edge` also revalidates affected downstream-connections. It follows resolved If outputs and collector chains, checking each affected If, collector, or iterator-once. Ordinary nodes end this dependency walk; unrelated unfinished nodes are not revalidated. If a check fails, the-new edge is removed and adjacency indexes are restored before the validation error is raised.+After inserting an edge into `If.true_input` or `If.false_input`, or into a collector's `item` or `collection`,+`add_edge` revalidates affected downstream connections. Collector input changes first pass that collector's candidate+validation, then the walk follows resolved If outputs and collector chains to check each affected If, collector, or+iterator once. Ordinary nodes end this dependency walk; unresolved If outputs and unrelated unfinished nodes are not+revalidated. If a check fails, the new edge is removed and adjacency indexes are restored before the validation error+is raised.### 3.4 Topology utilitiesdiff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.pyindex a28fbae5c7..fafdf568cc 100644--- a/invokeai/app/services/shared/graph_validation.py+++ b/invokeai/app/services/shared/graph_validation.py@@ -756,16 +756,25 @@ class Graph(BaseModel):list.append(self.edges, edge)self._add_edge_to_indexes(edge)try:- self._validate_if_branch_input_dependents(edge, destination_node)+ self._validate_type_dependents_after_edge(edge, destination_node)except Exception:self.delete_edge(edge)raiseelse:raise InvalidEdgeError()- def _validate_if_branch_input_dependents(self, edge: Edge, node: BaseInvocation) -> None:- """Revalidate type-dependent paths through Ifs and collectors after adding an If branch."""- if not isinstance(node, IfInvocation) or edge.destination.field not in ("true_input", "false_input"):+ def _validate_type_dependents_after_edge(self, edge: Edge, node: BaseInvocation) -> None:+ """Revalidate downstream collector and iterator contracts after a type-dependent edge change."""+ validate_start_node = True+ if isinstance(node, IfInvocation):+ if edge.destination.field not in ("true_input", "false_input"):+ return+ elif isinstance(node, CollectInvocation):+ if edge.destination.field not in (ITEM_FIELD, COLLECTION_FIELD):+ return+ # _validate_edge checked the collector with the candidate input before insertion.+ validate_start_node = False+ else:returnpending_nodes: list[IfInvocation | CollectInvocation | IterateInvocation] = [node]@@ -785,11 +794,12 @@ class Graph(BaseModel):continueif isinstance(source_node, CollectInvocation):- err = self._is_collector_connection_valid(source_node.id)- if err is not None:- raise InvalidEdgeError(- f"Collector output type does not match collector input type ({source_node.id}): {err}"- )+ if source_node.id != node.id or validate_start_node:+ err = self._is_collector_connection_valid(source_node.id)+ if err is not None:+ raise InvalidEdgeError(+ f"Collector output type does not match collector input type ({source_node.id}): {err}"+ )output_field = COLLECTION_FIELDelse:if self._get_effective_output_connections(source_node.id, "value") is None:@@ -2022,14 +2032,11 @@ class Graph(BaseModel):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)- if isinstance(source_node, CollectInvocation) and edge.source.field == COLLECTION_FIELD:- input_types.update(self._resolve_collector_input_types(source_node.id, visited.copy()))- continue-- 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))+ input_types.update(+ self._resolve_collection_input_types(+ [edge.source for edge in self._get_input_edges(node_id, COLLECTION_FIELD)], visited+ )+ )return input_types@@ -2103,15 +2110,38 @@ class Graph(BaseModel):if resolved_type != NoneType}- def _resolve_collection_input_types(self, collection_inputs: list[EdgeConnection]) -> set[Any]:+ def _resolve_collection_input_types(+ self, collection_inputs: list[EdgeConnection], visited_collectors: Optional[set[str]] = None+ ) -> set[Any]:+ visited_collectors = visited_collectors or set()input_field_types: set[Any] = set()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))+ input_field_types.update(self._resolve_collector_input_types(source_node.id, visited_collectors.copy()))+ continue++ if isinstance(source_node, IfInvocation) and input_conn.field == "value":+ sources = self._get_effective_output_connections(input_conn.node_id, input_conn.field)+ if sources is None:+ output_field_types = self._get_effective_output_field_types(input_conn.node_id, input_conn.field)+ for output_field_type in output_field_types:+ input_field_types.update(extract_collection_item_types(output_field_type))+ continue++ for source in sources:+ branch_source_node = self.get_node(source.node_id)+ if isinstance(branch_source_node, CollectInvocation) and source.field == COLLECTION_FIELD:+ input_field_types.update(+ self._resolve_collector_input_types(branch_source_node.id, visited_collectors.copy())+ )+ else:+ output_field_type = get_output_field_type(branch_source_node, source.field)+ input_field_types.update(extract_collection_item_types(output_field_type))continue- 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))++ for output_field_type in self._get_effective_output_field_types(input_conn.node_id, input_conn.field):+ input_field_types.update(extract_collection_item_types(output_field_type))return input_field_typesdef _validate_collector_collection_inputs(self, collection_input_field_types: list[Any]) -> str | None:diff --git a/tests/test_node_graph.py b/tests/test_node_graph.pyindex ee4a295b11..f2285726da 100644--- a/tests/test_node_graph.py+++ b/tests/test_node_graph.py@@ -25,6 +25,7 @@ from invokeai.app.invocations.primitives import (ColorInvocation,FloatCollectionInvocation,FloatInvocation,+ IntegerCollectionInvocation,IntegerInvocation,StringCollectionInvocation,StringInvocation,@@ -1242,6 +1243,116 @@ def test_graph_rejects_integer_iterator_output_for_mixed_numeric_collector(throuassert invalid_output_edge not in graph.edges+def test_graph_collector_rejects_new_input_that_invalidates_iterator_output():+ integer_source = IntegerInvocation(id="integer", value=1)+ float_source = FloatInvocation(id="float", value=2.5)+ collector = CollectInvocation(id="collect")+ iterator = IterateInvocation(id="iterate")+ integer_sink = IntegerInvocation(id="sink")+ graph = Graph(nodes={node.id: node for node in (integer_source, float_source, collector, iterator, integer_sink)})+ graph.add_edge(create_edge(integer_source.id, "value", collector.id, "item"))+ graph.add_edge(create_edge(collector.id, "collection", iterator.id, "collection"))+ graph.add_edge(create_edge(iterator.id, "item", integer_sink.id, "value"))+ graph.validate_self()++ invalid_input_edge = create_edge(float_source.id, "value", collector.id, "item")+ with pytest.raises(InvalidEdgeError):+ graph.add_edge(invalid_input_edge)++ assert invalid_input_edge not in graph.edges+ graph.validate_self()+++def test_graph_collector_rejects_new_input_that_invalidates_if_branch_iterator_output():+ integer_source = IntegerInvocation(id="integer", value=1)+ float_source = FloatInvocation(id="float", value=2.5)+ collector = CollectInvocation(id="collect")+ fallback = IntegerCollectionInvocation(id="fallback", collection=[2])+ if_node = IfInvocation(id="if")+ iterator = IterateInvocation(id="iterate")+ integer_sink = IntegerInvocation(id="sink")+ graph = Graph(+ nodes={+ node.id: node+ for node in (integer_source, float_source, collector, fallback, if_node, iterator, integer_sink)+ }+ )+ graph.add_edge(create_edge(integer_source.id, "value", collector.id, "item"))+ graph.add_edge(create_edge(collector.id, "collection", if_node.id, "true_input"))+ graph.add_edge(create_edge(fallback.id, "collection", if_node.id, "false_input"))+ graph.add_edge(create_edge(if_node.id, "value", iterator.id, "collection"))+ graph.add_edge(create_edge(iterator.id, "item", integer_sink.id, "value"))+ graph.validate_self()++ invalid_input_edge = create_edge(float_source.id, "value", collector.id, "item")+ with pytest.raises(InvalidEdgeError):+ graph.add_edge(invalid_input_edge)++ assert invalid_input_edge not in graph.edges+ graph.validate_self()+++def test_graph_collector_rejects_new_input_through_if_and_downstream_collector():+ integer_source = IntegerInvocation(id="integer", value=1)+ float_source = FloatInvocation(id="float", value=2.5)+ collector = CollectInvocation(id="collect")+ fallback = IntegerCollectionInvocation(id="fallback", collection=[2])+ if_node = IfInvocation(id="if")+ downstream_collector = CollectInvocation(id="downstream_collect")+ iterator = IterateInvocation(id="iterate")+ integer_sink = IntegerInvocation(id="sink")+ graph = Graph(+ nodes={+ node.id: node+ for node in (+ integer_source,+ float_source,+ collector,+ fallback,+ if_node,+ downstream_collector,+ iterator,+ integer_sink,+ )+ }+ )+ graph.add_edge(create_edge(integer_source.id, "value", collector.id, "item"))+ graph.add_edge(create_edge(collector.id, "collection", if_node.id, "true_input"))+ graph.add_edge(create_edge(fallback.id, "collection", if_node.id, "false_input"))+ graph.add_edge(create_edge(if_node.id, "value", downstream_collector.id, "collection"))+ graph.add_edge(create_edge(downstream_collector.id, "collection", iterator.id, "collection"))+ graph.add_edge(create_edge(iterator.id, "item", integer_sink.id, "value"))+ graph.validate_self()++ invalid_input_edge = create_edge(float_source.id, "value", collector.id, "item")+ with pytest.raises(InvalidEdgeError):+ graph.add_edge(invalid_input_edge)++ assert invalid_input_edge not in graph.edges+ graph.validate_self()+++def test_graph_collector_revalidation_ignores_unrelated_incomplete_nodes():+ first_source = StringInvocation(id="first", value="one")+ second_source = StringInvocation(id="second", value="two")+ collector = CollectInvocation(id="collect")+ unrelated_collector = CollectInvocation(id="unrelated_collect")+ unrelated_iterator = IterateInvocation(id="unrelated_iterate")+ graph = Graph(+ nodes={+ node.id: node for node in (first_source, second_source, collector, unrelated_collector, unrelated_iterator)+ }+ )++ first_edge = create_edge(first_source.id, "value", collector.id, "item")+ second_edge = create_edge(second_source.id, "value", collector.id, "item")+ graph.add_edge(first_edge)+ graph.add_edge(second_edge)++ assert first_edge in graph.edges+ assert second_edge in graph.edges++def test_graph_rejects_iterator_consumers_incompatible_with_if_collector_branches():graph = Graph()string_value = StringInvocation(id="string", value="text")