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: validate transitive If dependents efficiently

JPPhoto0bee89a60207
diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.py
index 827b69344a..fc335e7f58 100644
--- a/invokeai/app/services/shared/graph_validation.py
+++ b/invokeai/app/services/shared/graph_validation.py
@@ -753,64 +753,70 @@ class Graph(BaseModel):
self._add_edge(edge, allow_inputless_source_collector=False)
def _add_edge(self, edge: Edge, allow_inputless_source_collector: bool) -> None:
- self._validate_edge(edge, allow_inputless_source_collector)
+ destination_node = self._validate_edge(edge, allow_inputless_source_collector)
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)
+ self._validate_if_branch_input_dependents(edge, destination_node)
except Exception:
self.delete_edge(edge)
raise
else:
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)
+ 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"):
return
- pending_node_ids = [node.id]
+ pending_nodes: list[IfInvocation | CollectInvocation | IterateInvocation] = [node]
validated_node_ids: set[str] = set()
- while pending_node_ids:
- node_id = pending_node_ids.pop()
- if node_id in validated_node_ids:
+ while pending_nodes:
+ source_node = pending_nodes.pop()
+ if source_node.id in validated_node_ids:
continue
- validated_node_ids.add(node_id)
+ validated_node_ids.add(source_node.id)
- if self._get_effective_output_connections(node_id, "value") is None:
+ if isinstance(source_node, IterateInvocation):
+ err = self._is_iterator_connection_valid(source_node.id)
+ if err is not None:
+ raise InvalidEdgeError(
+ f"Iterator input type does not match iterator output type ({source_node.id}): {err}"
+ )
continue
- for output_edge in self._get_output_edges(node_id, "value"):
+ if 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}"
+ )
+ output_field = COLLECTION_FIELD
+ else:
+ if self._get_effective_output_connections(source_node.id, "value") is None:
+ continue
+ output_field = "value"
+
+ for output_edge in self._get_output_edges(source_node.id, output_field):
destination_node = self.get_node(output_edge.destination.node_id)
- self._validate_edge_field_compatibility(output_edge, destination_node)
+ self._validate_edge_field_compatibility(output_edge, source_node, destination_node)
- if (
- isinstance(destination_node, IterateInvocation)
- and output_edge.destination.field == COLLECTION_FIELD
+ if isinstance(destination_node, IfInvocation) and output_edge.destination.field in (
+ "true_input",
+ "false_input",
):
- 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 (
+ pending_nodes.append(destination_node)
+ elif 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_nodes.append(destination_node)
+ elif (
+ isinstance(destination_node, IterateInvocation)
+ and output_edge.destination.field == COLLECTION_FIELD
):
- pending_node_ids.append(destination_node.id)
+ pending_nodes.append(destination_node)
def _extend_edges_unchecked(self, edges: Iterable[Edge]) -> None:
"""Adds trusted runtime edges without author-time graph validation.
@@ -883,8 +889,9 @@ class Graph(BaseModel):
):
continue
self._validate_edge_not_to_direct_input(edge, destination_node)
+ source_node = self.get_node(edge.source.node_id)
if not self._are_effective_connections_compatible(
- edge.source.node_id, edge.source.field, destination_node, edge.destination.field
+ source_node, edge.source.field, destination_node, edge.destination.field
):
raise InvalidEdgeError(f"Edge source and target types do not match ({edge})")
@@ -1005,14 +1012,16 @@ 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, destination_node: BaseInvocation) -> None:
+ def _validate_edge_field_compatibility(
+ self, edge: Edge, source_node: BaseInvocation, destination_node: BaseInvocation
+ ) -> None:
if isinstance(destination_node, CallSavedWorkflowInvocation) and is_call_saved_workflow_dynamic_input(
edge.destination.field
):
return
self._validate_edge_not_to_direct_input(edge, destination_node)
if not self._are_effective_connections_compatible(
- edge.source.node_id, edge.source.field, destination_node, edge.destination.field
+ source_node, edge.source.field, destination_node, edge.destination.field
):
raise InvalidEdgeError(f"Field types are incompatible ({edge})")
@@ -1088,18 +1097,19 @@ class Graph(BaseModel):
if err is not None:
raise InvalidEdgeError(f"Collector input type does not match collector output type ({edge}): {err}")
- def _validate_edge(self, edge: Edge, allow_inputless_source_collector: bool = False):
- """Validates that a new edge doesn't create a cycle in the graph"""
+ def _validate_edge(self, edge: Edge, allow_inputless_source_collector: bool = False) -> BaseInvocation:
+ """Validate a new edge and return its destination for post-insertion validation."""
self._validate_reserved_edge_fields(edge)
source_node, destination_node = self._get_edge_nodes(edge)
if edge.type == "loop_linkage":
self._validate_loop_linkage_edge(edge, source_node, destination_node)
- return
+ return destination_node
self._validate_edge_destination_uniqueness(edge, destination_node)
self._validate_edge_would_not_create_cycle(edge)
- self._validate_edge_field_compatibility(edge, destination_node)
+ self._validate_edge_field_compatibility(edge, source_node, 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)
+ return destination_node
def has_node(self, node_id: str) -> bool:
"""Determines whether or not a node exists in the graph."""
@@ -1992,15 +2002,16 @@ class Graph(BaseModel):
def _are_effective_connections_compatible(
self,
- source_node_id: str,
+ source_node: BaseInvocation,
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 not isinstance(source_node, IfInvocation) or source_field != "value":
+ return are_connections_compatible(source_node, source_field, destination_node, destination_field)
+ 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)
diff --git a/tests/test_node_graph.py b/tests/test_node_graph.py
index 2366f4b04d..b13a507657 100644
--- a/tests/test_node_graph.py
+++ b/tests/test_node_graph.py
@@ -1210,25 +1210,114 @@ def test_graph_rejects_iterator_consumers_incompatible_with_if_collector_branche
graph.add_edge(create_edge(iterator.id, "item", string_sink.id, "value"))
-def test_graph_skips_if_traversal_state_for_non_if_sources(monkeypatch: pytest.MonkeyPatch):
- from invokeai.app.services.shared import graph_validation
[email protected]("collector_count", [1, 3])
+def test_graph_rejects_if_branch_that_invalidates_iterator_through_collectors(collector_count: int):
+ true_value = StringInvocation(id="true", value="true")
+ false_value = StringInvocation(id="false", value="false")
+ if_node = IfInvocation(id="if")
+ collectors = [CollectInvocation(id=f"collect_{index}") for index in range(collector_count)]
+ iterator = IterateInvocation(id="iterator")
+ image_sink = ImageToImageTestInvocation(id="image_sink")
+ string_sink = StringInvocation(id="string_sink")
+ nodes = [true_value, false_value, if_node, *collectors, iterator, image_sink, string_sink]
+ image_edge = create_edge(iterator.id, "item", image_sink.id, "image")
+ graph = Graph(
+ nodes={node.id: node for node in nodes},
+ edges=[
+ create_edge(true_value.id, "value", if_node.id, "true_input"),
+ create_edge(if_node.id, "value", collectors[0].id, "item"),
+ *[
+ create_edge(source.id, "collection", target.id, "collection")
+ for source, target in zip(collectors, collectors[1:], strict=False)
+ ],
+ create_edge(collectors[-1].id, "collection", iterator.id, "collection"),
+ image_edge,
+ ],
+ )
+ graph.validate_self()
+ original_edges = list(graph.edges)
+ branch_edge = create_edge(false_value.id, "value", if_node.id, "false_input")
- string_value = StringInvocation(id="string", value="text")
- graph = Graph(nodes={string_value.id: string_value})
- set_calls = 0
- original_set = set
+ with pytest.raises(InvalidEdgeError, match="[Ii]terator.*type"):
+ graph.add_edge(branch_edge)
- def count_set_calls(*args: Any, **kwargs: Any) -> set[Any]:
- nonlocal set_calls
- set_calls += 1
- return original_set(*args, **kwargs)
+ assert graph.edges == original_edges
+ graph.validate_self()
+
+ graph.delete_edge(image_edge)
+ graph.add_edge(create_edge(iterator.id, "item", string_sink.id, "value"))
+ graph.add_edge(branch_edge)
+ graph.validate_self()
- monkeypatch.setattr(graph_validation, "set", count_set_calls, raising=False)
- assert graph._get_effective_output_connections(string_value.id, "value") == [
- EdgeConnection(node_id=string_value.id, field="value")
+def test_graph_if_branch_revalidates_only_affected_iterators_once(monkeypatch: pytest.MonkeyPatch):
+ nodes = [
+ StringInvocation(id="true", value="true"),
+ StringInvocation(id="false", value="false"),
+ IfInvocation(id="if"),
+ CollectInvocation(id="first_collect"),
+ CollectInvocation(id="second_collect"),
+ IterateInvocation(id="affected_iterator"),
+ StringInvocation(id="sink"),
+ *[IterateInvocation(id=f"unrelated_{index}") for index in range(32)],
]
- assert set_calls == 0
+ graph = Graph(
+ nodes={node.id: node for node in nodes},
+ edges=[
+ create_edge("true", "value", "if", "true_input"),
+ create_edge("if", "value", "first_collect", "item"),
+ create_edge("if", "value", "second_collect", "item"),
+ create_edge("first_collect", "collection", "second_collect", "collection"),
+ create_edge("second_collect", "collection", "affected_iterator", "collection"),
+ create_edge("affected_iterator", "item", "sink", "value"),
+ ],
+ )
+ validated_iterators: list[str] = []
+ original_validate_iterator = Graph._is_iterator_connection_valid
+
+ def count_iterator_validations(graph: Graph, node_id: str, *args: Any, **kwargs: Any):
+ validated_iterators.append(node_id)
+ return original_validate_iterator(graph, node_id, *args, **kwargs)
+
+ monkeypatch.setattr(Graph, "_is_iterator_connection_valid", count_iterator_validations)
+ graph.add_edge(create_edge("false", "value", "if", "false_input"))
+
+ assert 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
+ 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)
+
+ def count_connection_allocations(connection: EdgeConnection, **kwargs: Any):
+ nonlocal connection_allocations
+ connection_allocations += 1
+ original_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()
+
+ assert graph.edges == edges
+ assert (node_lookups, connection_allocations) == (2 * len(edges), 0)
def test_graph_validation_bounds_shared_if_branch_validation_work(monkeypatch: pytest.MonkeyPatch):