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(graph): validate collector edits consistently

JPPhoto7037d0ed558d
diff --git a/docs/src/content/docs/Users Guide/08.Workflows/loop-nodes.mdx b/docs/src/content/docs/Users Guide/08.Workflows/loop-nodes.mdx
index 69bd4d75c6..a568db104c 100644
--- a/docs/src/content/docs/Users Guide/08.Workflows/loop-nodes.mdx
+++ b/docs/src/content/docs/Users Guide/08.Workflows/loop-nodes.mdx
@@ -225,6 +225,18 @@ An empty collection is a successful loop with zero body iterations:
Set `ForReturn.continue_condition` to `False` when the loop should stop after the current item. The results and state
from completed iterations remain available through the normal final outputs.
+## Collection Type Checks
+
+Before a workflow runs, InvokeAI checks the item types flowing through `Collect`, `Iterate`, and connected `If` nodes.
+An `int` and a `float` collected together have the common item type `float`, so an iterator consumer must accept a
+float. If both resolved branches of an `If` feed one `Collect.collection`, their possible item types must share one
+compatible root. For example, `If(Collect[int], StringCollection) -> Collect.collection` is rejected even though only
+one branch runs at a time; the resulting collection cannot have one statically known item type. Complete both `If`
+branches before relying on strict type validation or queueing the workflow.
+
+A workflow saved before stricter collection checks may now fail validation when queued. Follow the validation error to
+the collector or iterator connection, then update the workflow so its collection item types and consumers agree.
+
## Common Wiring Mistakes
- Connect the collection to `For.collection`, not to `For.item`.
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 4a76664d03..c6feae5f73 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -209,10 +209,15 @@ Runs a sequence of checks:
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.
+ - When an `If.value` feeds a typed collection input, each resolved collector branch is checked against the target
+ using its inferred item root. When an `If.value` feeds `Collect.collection`, the possible item roots from all
+ resolved branches must have one compatible root; mutually exclusive branches do not permit a heterogeneous
+ collector input. For example, `If(Collect[int], StringCollection) -> Collect.collection` is rejected.
- 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
- inference). The graph's separate DAG check rejects cycles before projection.
+ inference), and stop downstream incremental type revalidation at that unresolved `If`. The graph's separate DAG
+ check rejects cycles before projection.
- This widens compatibility: a direct collector with both `int` and `float` items, previously rejected, now resolves
to `float`. Its downstream consumers must accept floats; unrelated mixed item types remain invalid.
- Ordinary source ports use the direct compatibility path with already resolved nodes, without If traversal or
@@ -247,11 +252,13 @@ Checks a single prospective edge before insertion:
- Iterator/collector constraints re-checked when the edge creates relevant patterns.
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.
+`add_edge` revalidates affected connections in both directions. Candidate collector checks validate local roots before
+insertion; after insertion, the walk checks upstream collectors against their updated downstream roots, then follows
+resolved If outputs and collector chains to check affected collectors and iterators once. Ordinary nodes end this
+dependency walk; unresolved If outputs and unrelated unfinished nodes are not revalidated. When a plain item is added
+to a collector whose concrete root is unchanged and whose only consumers are direct iterators, iterator output types
+are checked against that known root without resolving the same collector again. If a check fails, the new edge is
+removed and adjacency indexes are restored before the validation error is raised.
### 3.4 Topology utilities
@@ -261,9 +268,18 @@ is raised.
### 3.5 Mutation helpers
-- `add_node`, `update_node` (preserve edges, rewrite endpoints if id changes), `delete_node`.
+- `add_node`, `update_node` (preserve edges, rewrite endpoints if id changes; failed rewrites restore the original node
+ and edges, then invalidate lazy adjacency indexes so later lookups rebuild them), `delete_node`.
- `add_edge`, `delete_edge` (with validation).
+### 3.6 Compatibility
+
+Graph validation runs when a workflow is queued and when a persisted runtime session is hydrated. New inferred collector
+root checks can therefore reject an older saved workflow at enqueue time, or make a pending queue snapshot unreadable
+when the queue worker restores it. Unreadable pending snapshots are marked failed and retained for recovery by the
+queue's quarantine path; they are not silently executed. The workflow can be edited to make collector inputs and
+consumers agree with the inferred root before it is queued again.
+
## 4) GraphExecutionState (runtime)
Holds the state for a single run. Keeps the source graph intact and materializes a separate execution graph.
diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.py
index f325568296..352f613133 100644
--- a/invokeai/app/services/shared/graph_validation.py
+++ b/invokeai/app/services/shared/graph_validation.py
@@ -763,8 +763,109 @@ class Graph(BaseModel):
else:
raise InvalidEdgeError()
+ def _get_upstream_collector_ids(self, node: BaseInvocation) -> list[str]:
+ """Find collectors whose inferred item types contribute to this node's input types."""
+ if isinstance(node, CollectInvocation):
+ input_edges = [
+ *self._get_input_edges(node.id, ITEM_FIELD),
+ *self._get_input_edges(node.id, COLLECTION_FIELD),
+ ]
+ elif isinstance(node, IterateInvocation):
+ input_edges = self._get_input_edges(node.id, COLLECTION_FIELD)
+ elif isinstance(node, IfInvocation):
+ input_edges = [
+ *self._get_input_edges(node.id, "true_input"),
+ *self._get_input_edges(node.id, "false_input"),
+ ]
+ else:
+ return []
+
+ pending = [edge.source for edge in input_edges]
+ visited_connections: set[tuple[str, str]] = set()
+ visited_collectors: set[str] = set()
+ upstream_collectors: list[str] = []
+
+ while pending:
+ connection = pending.pop()
+ key = (connection.node_id, connection.field)
+ if key in visited_connections:
+ continue
+ visited_connections.add(key)
+
+ source_node = self.get_node(connection.node_id)
+ if isinstance(source_node, CollectInvocation) and connection.field == COLLECTION_FIELD:
+ if source_node.id in visited_collectors:
+ continue
+ visited_collectors.add(source_node.id)
+ input_edges = [
+ *self._get_input_edges(source_node.id, ITEM_FIELD),
+ *self._get_input_edges(source_node.id, COLLECTION_FIELD),
+ ]
+ if input_edges:
+ pending.extend(edge.source for edge in input_edges)
+ upstream_collectors.append(source_node.id)
+ elif isinstance(source_node, IterateInvocation) and connection.field == ITEM_FIELD:
+ pending.extend(edge.source for edge in self._get_input_edges(source_node.id, COLLECTION_FIELD))
+ elif isinstance(source_node, IfInvocation) and connection.field == "value":
+ sources = self._get_effective_output_connections(source_node.id, connection.field)
+ if sources is not None:
+ pending.extend(sources)
+
+ return upstream_collectors
+
+ def _get_unchanged_root_iterators(self, edge: Edge, node: BaseInvocation) -> set[str]:
+ """Return direct Iterate consumers safe to skip when a plain item leaves a collector root unchanged."""
+ if not isinstance(node, CollectInvocation) or edge.destination.field != ITEM_FIELD:
+ return set()
+
+ source_node = self.get_node(edge.source.node_id)
+ if isinstance(source_node, (CollectInvocation, IfInvocation, IterateInvocation)):
+ return set()
+
+ new_item_type = get_output_field_type(source_node, edge.source.field)
+ if new_item_type is Any or get_origin(new_item_type) is not None:
+ return set()
+
+ existing_item_edges = [
+ input_edge for input_edge in self._get_input_edges(node.id, ITEM_FIELD) if input_edge != edge
+ ]
+ if not existing_item_edges or self._get_input_edges(node.id, COLLECTION_FIELD):
+ return set()
+ for existing_edge in existing_item_edges:
+ existing_source = self.get_node(existing_edge.source.node_id)
+ if isinstance(existing_source, (CollectInvocation, IfInvocation, IterateInvocation)):
+ return set()
+ if get_output_field_type(existing_source, existing_edge.source.field) != new_item_type:
+ return set()
+
+ outputs = self._get_output_edges(node.id, COLLECTION_FIELD)
+ if not outputs:
+ return set()
+
+ unchanged_root_iterators: set[str] = set()
+ for output_edge in outputs:
+ iterator = self.get_node(output_edge.destination.node_id)
+ if (
+ not isinstance(iterator, IterateInvocation)
+ or output_edge.destination.field != COLLECTION_FIELD
+ or self._get_input_edges(iterator.id, COLLECTION_FIELD) != [output_edge]
+ ):
+ return set()
+
+ output_types = self._get_iterator_output_field_types(
+ [edge.destination for edge in self._get_output_edges(iterator.id, ITEM_FIELD)]
+ )
+ error = self._validate_iterator_output_types(list[new_item_type], output_types)
+ if error is not None:
+ raise InvalidEdgeError(
+ f"Iterator input type does not match iterator output type ({iterator.id}): {error}"
+ )
+ unchanged_root_iterators.add(iterator.id)
+
+ return unchanged_root_iterators
+
def _validate_type_dependents_after_edge(self, edge: Edge, node: BaseInvocation) -> None:
- """Revalidate downstream collector and iterator contracts after a type-dependent edge change."""
+ """Revalidate affected upstream collectors and downstream collector/iterator contracts after edge changes."""
validate_start_node = True
if isinstance(node, IfInvocation):
if edge.destination.field not in ("true_input", "false_input"):
@@ -777,7 +878,10 @@ class Graph(BaseModel):
else:
return
- pending_nodes: list[IfInvocation | CollectInvocation | IterateInvocation] = [node]
+ unchanged_root_iterators = self._get_unchanged_root_iterators(edge, node)
+ upstream_nodes = [self.get_node(node_id) for node_id in self._get_upstream_collector_ids(node)]
+ pending_nodes: list[IfInvocation | CollectInvocation | IterateInvocation] = [*upstream_nodes, node]
+ pending_node_ids = {source_node.id for source_node in pending_nodes}
validated_node_ids: set[str] = set()
while pending_nodes:
source_node = pending_nodes.pop()
@@ -786,11 +890,12 @@ class Graph(BaseModel):
validated_node_ids.add(source_node.id)
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}"
- )
+ if source_node.id not in unchanged_root_iterators:
+ 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
if isinstance(source_node, CollectInvocation):
@@ -814,17 +919,23 @@ class Graph(BaseModel):
"true_input",
"false_input",
):
- pending_nodes.append(destination_node)
+ if destination_node.id not in pending_node_ids:
+ pending_nodes.append(destination_node)
+ pending_node_ids.add(destination_node.id)
elif isinstance(destination_node, CollectInvocation) and output_edge.destination.field in (
ITEM_FIELD,
COLLECTION_FIELD,
):
- pending_nodes.append(destination_node)
+ if destination_node.id not in pending_node_ids:
+ pending_nodes.append(destination_node)
+ pending_node_ids.add(destination_node.id)
elif (
isinstance(destination_node, IterateInvocation)
and output_edge.destination.field == COLLECTION_FIELD
):
- pending_nodes.append(destination_node)
+ if destination_node.id not in pending_node_ids:
+ pending_nodes.append(destination_node)
+ pending_node_ids.add(destination_node.id)
def _extend_edges_unchecked(self, edges: Iterable[Edge]) -> None:
"""Adds trusted runtime edges without author-time graph validation.
@@ -1086,7 +1197,10 @@ class Graph(BaseModel):
) -> None:
if isinstance(destination_node, CollectInvocation) and edge.destination.field in (ITEM_FIELD, COLLECTION_FIELD):
err = self._is_collector_connection_valid(
- edge.destination.node_id, new_input=edge.source, new_input_field=edge.destination.field
+ edge.destination.node_id,
+ new_input=edge.source,
+ new_input_field=edge.destination.field,
+ validate_downstream_outputs=False,
)
if err is not None:
raise InvalidEdgeError(f"Collector output type does not match collector input type ({edge}): {err}")
@@ -1101,7 +1215,9 @@ class Graph(BaseModel):
edge.destination.node_id == source_node.id for edge in self.edges
):
return
- err = self._is_collector_connection_valid(edge.source.node_id, new_output=edge.destination)
+ err = self._is_collector_connection_valid(
+ edge.source.node_id, new_output=edge.destination, validate_downstream_outputs=False
+ )
if err is not None:
raise InvalidEdgeError(f"Collector input type does not match collector output type ({edge}): {err}")
@@ -1146,9 +1262,16 @@ class Graph(BaseModel):
if new_node.id != node.id and self.has_node(new_node.id):
raise NodeAlreadyInGraphError(f"Node with id {new_node.id} already exists in graph")
- # Set the new node in the graph
- self.nodes[new_node.id] = new_node
- if new_node.id != node.id:
+ if new_node.id == node.id:
+ self.nodes[new_node.id] = new_node
+ return
+
+ original_nodes = self.nodes.copy()
+ original_edges = list(self.edges)
+
+ try:
+ # Set the new node in the graph
+ self.nodes[new_node.id] = new_node
input_edges = self._get_input_edges(node_id, include_loop_linkage=True)
output_edges = self._get_output_edges(node_id, include_loop_linkage=True)
@@ -1173,6 +1296,11 @@ class Graph(BaseModel):
destination=edge.destination,
)
)
+ except Exception:
+ self.nodes.clear()
+ self.nodes.update(original_nodes)
+ self.edges[:] = original_edges
+ raise
def _get_input_edges(
self, node_id: str, field: Optional[str] = None, *, include_loop_linkage: bool = False
@@ -2014,10 +2142,26 @@ class Graph(BaseModel):
sources = self._get_effective_output_connections(source_node.id, source_field)
if sources is None:
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
+
+ destination_item_types = extract_collection_item_types(
+ get_input_field_type(destination_node, destination_field)
)
+ check_collector_roots = bool(destination_item_types) and Any not in destination_item_types
+ for source in sources:
+ branch_node = self.get_node(source.node_id)
+ if not are_connections_compatible(branch_node, source.field, destination_node, destination_field):
+ return False
+ if (
+ check_collector_roots
+ and isinstance(branch_node, CollectInvocation)
+ and source.field == COLLECTION_FIELD
+ ):
+ branch_root_type = self._get_collector_input_root_type(branch_node.id)
+ if branch_root_type is not None and not any(
+ are_connection_types_compatible(branch_root_type, item_type) for item_type in destination_item_types
+ ):
+ return False
+ return True
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."""
@@ -2120,10 +2264,6 @@ class Graph(BaseModel):
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, visited_collectors))
- 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:
@@ -2131,20 +2271,18 @@ class Graph(BaseModel):
for output_field_type in output_field_types:
input_field_types.update(extract_collection_item_types(output_field_type))
continue
+ else:
+ sources = [input_conn]
- 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)
- )
- 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 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))
+ 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)
+ )
+ else:
+ output_field_type = get_output_field_type(branch_source_node, source.field)
+ input_field_types.update(extract_collection_item_types(output_field_type))
return input_field_types
def _validate_collector_collection_inputs(self, collection_input_field_types: list[Any]) -> str | None:
@@ -2207,6 +2345,7 @@ class Graph(BaseModel):
new_input: Optional[EdgeConnection] = None,
new_input_field: Optional[str] = None,
new_output: Optional[EdgeConnection] = None,
+ validate_downstream_outputs: bool = True,
) -> str | None:
item_inputs, collection_inputs, outputs = self._get_collector_connections(
node_id, new_input=new_input, new_input_field=new_input_field, new_output=new_output
@@ -2236,9 +2375,10 @@ class Graph(BaseModel):
if output_type_error is not None:
return output_type_error
- downstream_output_error = self._validate_downstream_collector_outputs(outputs, input_root_type)
- if downstream_output_error is not None:
- return downstream_output_error
+ if validate_downstream_outputs:
+ downstream_output_error = self._validate_downstream_collector_outputs(outputs, input_root_type)
+ if downstream_output_error is not None:
+ return downstream_output_error
return None
diff --git a/tests/app/services/session_queue/test_session_queue_dequeue.py b/tests/app/services/session_queue/test_session_queue_dequeue.py
index c9c7502db5..4aa0a529ea 100644
--- a/tests/app/services/session_queue/test_session_queue_dequeue.py
+++ b/tests/app/services/session_queue/test_session_queue_dequeue.py
@@ -9,6 +9,7 @@ from typing import Optional
import pytest
from pydantic_core import to_jsonable_python
+from invokeai.app.invocations.primitives import FloatInvocation, IntegerInvocation
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.events.events_common import QueueItemsRetriedEvent
from invokeai.app.services.invoker import Invoker
@@ -23,7 +24,14 @@ from invokeai.app.services.shared.execution_state_migration import (
dump_execution_state,
load_execution_state,
)
-from invokeai.app.services.shared.graph import Graph, GraphExecutionState
+from invokeai.app.services.shared.graph import (
+ CollectInvocation,
+ Edge,
+ EdgeConnection,
+ Graph,
+ GraphExecutionState,
+ IterateInvocation,
+)
from tests.test_nodes import TestEventService
_EMPTY_SESSION_JSON = json.dumps(to_jsonable_python(GraphExecutionState(graph=Graph()).model_dump()))
@@ -196,6 +204,60 @@ def test_fifo_quarantines_unreadable_snapshot_and_dequeues_later_work(
assert "Unable to load execution state" in error_message
+def test_fifo_quarantines_snapshot_with_invalid_collector_iterator_types(
+ session_queue_fifo: SqliteSessionQueue,
+) -> None:
+ nodes = [
+ IntegerInvocation(id="integer", value=1),
+ FloatInvocation(id="float", value=2.5),
+ CollectInvocation(id="collect"),
+ IterateInvocation(id="iterate"),
+ IntegerInvocation(id="sink", value=0),
+ ]
+ invalid_graph = Graph(
+ nodes={node.id: node for node in nodes},
+ edges=[
+ Edge(
+ source=EdgeConnection(node_id="integer", field="value"),
+ destination=EdgeConnection(node_id="collect", field="item"),
+ ),
+ Edge(
+ source=EdgeConnection(node_id="float", field="value"),
+ destination=EdgeConnection(node_id="collect", field="item"),
+ ),
+ Edge(
+ source=EdgeConnection(node_id="collect", field="collection"),
+ destination=EdgeConnection(node_id="iterate", field="collection"),
+ ),
+ Edge(
+ source=EdgeConnection(node_id="iterate", field="item"),
+ destination=EdgeConnection(node_id="sink", field="value"),
+ ),
+ ],
+ )
+ older_snapshot = json.loads(_EMPTY_SESSION_JSON)
+ older_snapshot["graph"] = to_jsonable_python(
+ invalid_graph.model_dump(mode="json", warnings=False, exclude_none=True)
+ )
+ invalid_item_id = _insert_queue_item(
+ session_queue_fifo,
+ "default",
+ "old-workflow-user",
+ session_json=json.dumps(older_snapshot),
+ )
+ valid_item_id = _insert_queue_item(session_queue_fifo, "default", "valid-user")
+
+ dequeued = session_queue_fifo.dequeue()
+
+ assert dequeued is not None
+ assert dequeued.item_id == valid_item_id
+ with session_queue_fifo._db.transaction() as cursor:
+ cursor.execute("SELECT status, error_message FROM session_queue WHERE item_id = ?", (invalid_item_id,))
+ status, error_message = cursor.fetchone()
+ assert status == "failed"
+ assert "Invalid iterator node" in error_message
+
+
def test_affinity_quarantines_unreadable_snapshot_and_dequeues_valid_work(
session_queue_round_robin: SqliteSessionQueue,
) -> None:
diff --git a/tests/test_node_graph.py b/tests/test_node_graph.py
index d16f57f825..8ffb5d94d2 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,
+ ImageCollectionInvocation,
IntegerCollectionInvocation,
IntegerInvocation,
StringCollectionInvocation,
@@ -1256,7 +1257,7 @@ def test_graph_collector_rejects_new_input_that_invalidates_iterator_output():
graph.validate_self()
invalid_input_edge = create_edge(float_source.id, "value", collector.id, "item")
- with pytest.raises(InvalidEdgeError):
+ with pytest.raises(InvalidEdgeError, match="Iterator input type does not match iterator output type"):
graph.add_edge(invalid_input_edge)
assert invalid_input_edge not in graph.edges
@@ -1285,7 +1286,7 @@ def test_graph_collector_rejects_new_input_that_invalidates_if_branch_iterator_o
graph.validate_self()
invalid_input_edge = create_edge(float_source.id, "value", collector.id, "item")
- with pytest.raises(InvalidEdgeError):
+ with pytest.raises(InvalidEdgeError, match="Iterator input type does not match iterator output type"):
graph.add_edge(invalid_input_edge)
assert invalid_input_edge not in graph.edges
@@ -1325,13 +1326,300 @@ def test_graph_collector_rejects_new_input_through_if_and_downstream_collector()
graph.validate_self()
invalid_input_edge = create_edge(float_source.id, "value", collector.id, "item")
- with pytest.raises(InvalidEdgeError):
+ with pytest.raises(InvalidEdgeError, match="Iterator input type does not match iterator output type"):
graph.add_edge(invalid_input_edge)
assert invalid_input_edge not in graph.edges
graph.validate_self()
+def test_graph_add_edge_revalidates_upstream_collector_after_downstream_item_change():
+ integer_collection = IntegerCollectionInvocation(id="integer_collection", collection=[1])
+ iterate = IterateInvocation(id="iterate")
+ upstream_collector = CollectInvocation(id="upstream_collect")
+ downstream_collector = CollectInvocation(id="downstream_collect")
+ float_source = FloatInvocation(id="float", value=2.5)
+ nodes = (integer_collection, iterate, upstream_collector, downstream_collector, float_source)
+ graph = Graph(
+ nodes={node.id: node for node in nodes},
+ edges=[
+ create_edge(integer_collection.id, "collection", iterate.id, "collection"),
+ create_edge(iterate.id, "item", upstream_collector.id, "item"),
+ create_edge(upstream_collector.id, "collection", downstream_collector.id, "collection"),
+ ],
+ )
+ graph.validate_self()
+ invalid_edge = create_edge(float_source.id, "value", downstream_collector.id, "item")
+ invalid_graph = Graph(nodes=graph.nodes, edges=[*graph.edges, invalid_edge])
+
+ with pytest.raises(InvalidEdgeError, match="Invalid collector node .*matching type"):
+ invalid_graph.validate_self()
+
+ with pytest.raises(InvalidEdgeError, match="Collector output type does not match collector input type"):
+ graph.add_edge(invalid_edge)
+
+ assert invalid_edge not in graph.edges
+ graph.validate_self()
+
+
+def test_graph_collector_edges_are_independent_of_add_order():
+ integer_one = IntegerInvocation(id="integer_one", value=1)
+ integer_two = IntegerInvocation(id="integer_two", value=2)
+ float_source = FloatInvocation(id="float", value=2.5)
+ first_collector = CollectInvocation(id="first_collect")
+ second_collector = CollectInvocation(id="second_collect")
+ nodes = (integer_one, integer_two, float_source, first_collector, second_collector)
+ edge_by_name = {
+ "integer_one": create_edge(integer_one.id, "value", first_collector.id, "item"),
+ "integer_two": create_edge(integer_two.id, "value", second_collector.id, "item"),
+ "collector_chain": create_edge(first_collector.id, "collection", second_collector.id, "collection"),
+ "float": create_edge(float_source.id, "value", first_collector.id, "item"),
+ }
+
+ def build_graph(edge_order: list[str]) -> Graph:
+ graph = Graph(nodes={node.id: node for node in nodes})
+ for edge_name in edge_order:
+ graph.add_edge(edge_by_name[edge_name])
+ graph.validate_self()
+ return graph
+
+ first_order_graph = build_graph(["integer_one", "collector_chain", "integer_two", "float"])
+ second_order_graph = build_graph(["integer_one", "float", "collector_chain", "integer_two"])
+
+ assert set(first_order_graph.edges) == set(second_order_graph.edges)
+
+ second_order_graph.update_node("float", FloatInvocation(id="float_replacement", value=3.5))
+
+ assert "float" not in second_order_graph.nodes
+ assert "float_replacement" in second_order_graph.nodes
+ assert create_edge("float_replacement", "value", first_collector.id, "item") in second_order_graph.edges
+ second_order_graph.validate_self()
+
+
+def test_graph_add_collection_input_revalidates_iterator_consumers():
+ integer_source = IntegerInvocation(id="integer", value=1)
+ float_collection = FloatCollectionInvocation(id="float_collection", collection=[2.5])
+ collector = CollectInvocation(id="collect")
+ iterate = IterateInvocation(id="iterate")
+ integer_sink = IntegerInvocation(id="integer_sink")
+ graph = Graph(
+ nodes={node.id: node for node in (integer_source, float_collection, collector, iterate, integer_sink)},
+ edges=[
+ create_edge(integer_source.id, "value", collector.id, "item"),
+ create_edge(collector.id, "collection", iterate.id, "collection"),
+ create_edge(iterate.id, "item", integer_sink.id, "value"),
+ ],
+ )
+ graph.validate_self()
+ invalid_edge = create_edge(float_collection.id, "collection", collector.id, "collection")
+
+ with pytest.raises(InvalidEdgeError, match="Iterator input type does not match iterator output type"):
+ graph.add_edge(invalid_edge)
+
+ assert invalid_edge not in graph.edges
+ graph.validate_self()
+
+
+def test_graph_collector_edit_keeps_unresolved_if_paths_editable():
+ first_value = IntegerInvocation(id="first", value=1)
+ second_value = IntegerInvocation(id="second", value=2)
+ fallback = IntegerCollectionInvocation(id="fallback", collection=[2])
+ collector = CollectInvocation(id="collect")
+ if_node = IfInvocation(id="if")
+ iterate = IterateInvocation(id="iterate")
+ integer_sink = IntegerInvocation(id="sink")
+ graph = Graph(
+ nodes={
+ node.id: node for node in (first_value, second_value, fallback, collector, if_node, iterate, integer_sink)
+ },
+ edges=[
+ create_edge(first_value.id, "value", collector.id, "item"),
+ create_edge(collector.id, "collection", if_node.id, "true_input"),
+ create_edge(fallback.id, "collection", if_node.id, "false_input"),
+ create_edge(if_node.id, "value", iterate.id, "collection"),
+ create_edge(iterate.id, "item", integer_sink.id, "value"),
+ ],
+ )
+ graph.validate_self()
+ false_branch_edge = create_edge(fallback.id, "collection", if_node.id, "false_input")
+ graph.delete_edge(false_branch_edge)
+ second_edge = create_edge(second_value.id, "value", collector.id, "item")
+
+ graph.add_edge(second_edge)
+
+ assert second_edge in graph.edges
+ assert false_branch_edge not in graph.edges
+
+
+def test_graph_validate_self_rejects_invalid_if_collector_iterator_graph():
+ integer_one = IntegerInvocation(id="integer_one", value=1)
+ float_value = FloatInvocation(id="float", value=2.5)
+ fallback = IntegerCollectionInvocation(id="fallback", collection=[2])
+ collector = CollectInvocation(id="collect")
+ if_node = IfInvocation(id="if")
+ downstream_collector = CollectInvocation(id="downstream_collect")
+ iterate = IterateInvocation(id="iterate")
+ integer_sink = IntegerInvocation(id="sink")
+ graph = Graph(
+ nodes={
+ node.id: node
+ for node in (
+ integer_one,
+ float_value,
+ fallback,
+ collector,
+ if_node,
+ downstream_collector,
+ iterate,
+ integer_sink,
+ )
+ },
+ edges=[
+ create_edge(integer_one.id, "value", collector.id, "item"),
+ create_edge(float_value.id, "value", collector.id, "item"),
+ create_edge(collector.id, "collection", if_node.id, "true_input"),
+ create_edge(fallback.id, "collection", if_node.id, "false_input"),
+ create_edge(if_node.id, "value", downstream_collector.id, "collection"),
+ create_edge(downstream_collector.id, "collection", iterate.id, "collection"),
+ create_edge(iterate.id, "item", integer_sink.id, "value"),
+ ],
+ )
+
+ with pytest.raises(InvalidEdgeError, match="Invalid iterator node .*type"):
+ graph.validate_self()
+
+
+def test_graph_update_node_restores_edges_after_reconnection_failure():
+ integer_value = IntegerInvocation(id="integer", value=1)
+ float_value = FloatInvocation(id="float", value=2.5)
+ collector = CollectInvocation(id="collect")
+ iterate = IterateInvocation(id="iterate")
+ integer_sink = IntegerInvocation(id="sink")
+ original_float_edge = create_edge(float_value.id, "value", collector.id, "item")
+ graph = Graph(
+ nodes={node.id: node for node in (integer_value, float_value, collector, iterate, integer_sink)},
+ edges=[
+ create_edge(integer_value.id, "value", collector.id, "item"),
+ original_float_edge,
+ create_edge(collector.id, "collection", iterate.id, "collection"),
+ create_edge(iterate.id, "item", integer_sink.id, "value"),
+ ],
+ )
+ original_nodes = dict(graph.nodes)
+ original_edges = list(graph.edges)
+
+ with pytest.raises(InvalidEdgeError, match="Iterator input type does not match iterator output type"):
+ graph.update_node("float", FloatInvocation(id="float_replacement", value=3.5))
+
+ assert graph.nodes == original_nodes
+ assert graph.edges == original_edges
+ assert graph._get_output_edges("float") == [original_float_edge]
+ assert original_float_edge in graph._get_input_edges("collect", "item")
+
+
+def test_graph_if_type_checks_use_inferred_collector_roots_for_typed_outputs():
+ integer_one = IntegerInvocation(id="integer_one", value=1)
+ float_one = FloatInvocation(id="float_one", value=2.5)
+ fallback = IntegerCollectionInvocation(id="fallback", collection=[2])
+ collector = CollectInvocation(id="collect")
+ if_node = IfInvocation(id="if")
+ integer_collection_sink = IntegerCollectionInvocation(id="integer_collection_sink", collection=[])
+ nodes = (integer_one, float_one, fallback, collector, if_node, integer_collection_sink)
+ base_edges = [
+ create_edge(integer_one.id, "value", collector.id, "item"),
+ create_edge(float_one.id, "value", collector.id, "item"),
+ create_edge(collector.id, "collection", if_node.id, "true_input"),
+ create_edge(fallback.id, "collection", if_node.id, "false_input"),
+ ]
+ invalid_edge = create_edge(if_node.id, "value", integer_collection_sink.id, "collection")
+ graph = Graph(nodes={node.id: node for node in nodes}, edges=base_edges)
+
+ with pytest.raises(InvalidEdgeError, match="Field types are incompatible"):
+ graph.add_edge(invalid_edge)
+
+ raw_graph = Graph(nodes={node.id: node for node in nodes}, edges=[*base_edges, invalid_edge])
+ with pytest.raises(InvalidEdgeError, match="Edge source and target types do not match"):
+ raw_graph.validate_self()
+
+
+def test_graph_if_rejects_integer_collector_for_optional_image_collection():
+ integer = IntegerInvocation(id="integer", value=1)
+ collector = CollectInvocation(id="integer_collect")
+ image_collection = ImageCollectionInvocation(id="image_collection")
+ if_node = IfInvocation(id="if")
+ image_sink = ImageCollectionInvocation(id="image_sink")
+ nodes = (integer, collector, image_collection, if_node, image_sink)
+ base_edges = [
+ create_edge(integer.id, "value", collector.id, "item"),
+ create_edge(collector.id, "collection", if_node.id, "true_input"),
+ create_edge(image_collection.id, "collection", if_node.id, "false_input"),
+ ]
+ invalid_edge = create_edge(if_node.id, "value", image_sink.id, "collection")
+ graph = Graph(nodes={node.id: node for node in nodes}, edges=base_edges)
+
+ with pytest.raises(InvalidEdgeError, match="Field types are incompatible"):
+ graph.add_edge(invalid_edge)
+
+ raw_graph = Graph(nodes={node.id: node for node in nodes}, edges=[*base_edges, invalid_edge])
+ with pytest.raises(InvalidEdgeError, match="Edge source and target types do not match"):
+ raw_graph.validate_self()
+
+
+def test_graph_collect_rejects_distinct_item_roots_from_if_branches():
+ integer_source = IntegerInvocation(id="integer", value=1)
+ integer_collector = CollectInvocation(id="integer_collect")
+ string_collection = StringCollectionInvocation(id="string_collection", collection=["text"])
+ if_node = IfInvocation(id="if")
+ downstream_collector = CollectInvocation(id="downstream_collect")
+ nodes = (integer_source, integer_collector, string_collection, if_node, downstream_collector)
+ edges = [
+ create_edge(integer_source.id, "value", integer_collector.id, "item"),
+ create_edge(integer_collector.id, "collection", if_node.id, "true_input"),
+ create_edge(string_collection.id, "collection", if_node.id, "false_input"),
+ ]
+ invalid_edge = create_edge(if_node.id, "value", downstream_collector.id, "collection")
+ graph = Graph(nodes={node.id: node for node in nodes}, edges=edges)
+
+ with pytest.raises(InvalidEdgeError, match="Collector input collection items must be of a single type"):
+ graph.add_edge(invalid_edge)
+
+ invalid_graph = Graph(nodes={node.id: node for node in nodes}, edges=[*edges, invalid_edge])
+ with pytest.raises(InvalidEdgeError, match="Invalid collector node .*single type"):
+ invalid_graph.validate_self()
+
+
+def test_graph_collect_accepts_numeric_if_branch_roots():
+ integer_source = IntegerInvocation(id="integer", value=1)
+ integer_collector = CollectInvocation(id="integer_collect")
+ float_collection = FloatCollectionInvocation(id="float_collection", collection=[2.5])
+ if_node = IfInvocation(id="if")
+ downstream_collector = CollectInvocation(id="downstream_collect")
+ iterate = IterateInvocation(id="iterate")
+ float_sink = FloatInvocation(id="sink", value=0.0)
+ nodes = (
+ integer_source,
+ integer_collector,
+ float_collection,
+ if_node,
+ downstream_collector,
+ iterate,
+ float_sink,
+ )
+ graph = Graph(
+ nodes={node.id: node for node in nodes},
+ edges=[
+ create_edge(integer_source.id, "value", integer_collector.id, "item"),
+ create_edge(integer_collector.id, "collection", if_node.id, "true_input"),
+ create_edge(float_collection.id, "collection", if_node.id, "false_input"),
+ create_edge(if_node.id, "value", downstream_collector.id, "collection"),
+ create_edge(downstream_collector.id, "collection", iterate.id, "collection"),
+ create_edge(iterate.id, "item", float_sink.id, "value"),
+ ],
+ )
+
+ 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")
@@ -1410,6 +1698,44 @@ def test_graph_collector_validation_bounds_shared_if_type_resolution(monkeypatch
assert max(resolution_counts) <= 4 * layers
+def test_graph_collector_item_add_does_not_repeat_iterator_collector_resolution(monkeypatch: pytest.MonkeyPatch):
+ sources = [IntegerInvocation(id=f"integer_{index}", value=index) for index in range(3)]
+ collector = CollectInvocation(id="collect")
+ iterate = IterateInvocation(id="iterate")
+ sink = IntegerInvocation(id="sink")
+ graph = Graph(
+ nodes={node.id: node for node in (*sources, collector, iterate, sink)},
+ edges=[
+ create_edge(sources[0].id, "value", collector.id, "item"),
+ create_edge(sources[1].id, "value", collector.id, "item"),
+ create_edge(collector.id, "collection", iterate.id, "collection"),
+ create_edge(iterate.id, "item", sink.id, "value"),
+ ],
+ )
+ resolution_count = 0
+ iterator_validation_count = 0
+ original_resolve = Graph._resolve_collector_input_types
+ original_validate_iterator = Graph._is_iterator_connection_valid
+
+ def count_resolutions(graph: Graph, node_id: str, visited: set[str] | None = None) -> set[Any]:
+ nonlocal resolution_count
+ resolution_count += 1
+ return original_resolve(graph, node_id, visited)
+
+ def count_iterator_validations(graph: Graph, node_id: str, *args: Any, **kwargs: Any) -> str | None:
+ nonlocal iterator_validation_count
+ iterator_validation_count += 1
+ return original_validate_iterator(graph, node_id, *args, **kwargs)
+
+ monkeypatch.setattr(Graph, "_resolve_collector_input_types", count_resolutions)
+ monkeypatch.setattr(Graph, "_is_iterator_connection_valid", count_iterator_validations)
+
+ graph.add_edge(create_edge(sources[2].id, "value", collector.id, "item"))
+
+ assert iterator_validation_count == 0
+ assert resolution_count == 0
+
+
def test_graph_rejects_iterator_consumers_incompatible_with_if_collector_branches():
graph = Graph()
string_value = StringInvocation(id="string", value="text")