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.

refactor(execution): plan body-mediated fan-in

JPPhoto7a67edab6ee7
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 9620227f9d..ca6ac41870 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -113,8 +113,17 @@ its ordered values; a missing stream falls back to materialized results for lega
consumers from `Collect.collection` use a private graph-state planner for prepared-copy expansion, iteration paths,
and the empty-stream barrier. The exact fresh two-source/two-`Iterate`/shared-`Collect.item` and exact fresh
three-source/three-`Iterate`/shared-`Collect.item` fan-in shapes also use the planner for independent stream expansion,
-closure gating, and deterministic source-ordered hydration. Fan-in with four or more branches, nested or input-driven
-iterators, and mixed control flow remain on the compatibility materializer for those responsibilities.
+closure gating, and deterministic source-ordered hydration. The exact fresh two-branch body-mediated shape,
+`source_a -> Iterate_a -> body_a -> Collect.item` plus
+`source_b -> Iterate_b -> body_b -> Collect.item`, is also planner-owned:
+source IDs are ordered lexically, branch order is preserved, and `Collect` waits
+for both streams to close, including empty streams. This is a private bounded
+planner case with exactly seven nodes and six ordinary edges: two inputless
+ordinary sources, two `Iterate` nodes, two ordinary bodies, and one `Collect`.
+It has no `Collect.collection` input, downstream consumer, or extra topology.
+Three or more body-mediated
+branches, fan-in with four or more direct branches, nested or input-driven
+iterators, and mixed control flow remain on the compatibility materializer.
Focused compatibility coverage now proves empty, nested, fan-in, partial/rehydrated, failed, canceled, and retried
Iterate/Collect sessions. This is evidence for the current adapters; it does not remove materialization or queue
ownership. Direct `Iterate`/`Collect`-only graphs and the exact bounded nested shape now use the generic scheduler
diff --git a/docs/src/content/docs/features/Workflows/loop-nodes.mdx b/docs/src/content/docs/features/Workflows/loop-nodes.mdx
index 5e867a50e6..5eb675d377 100644
--- a/docs/src/content/docs/features/Workflows/loop-nodes.mdx
+++ b/docs/src/content/docs/features/Workflows/loop-nodes.mdx
@@ -187,7 +187,9 @@ Collect.collection -> ForReturn.output
The outer loop waits for the inner `Iterate` and `Collect` to finish, then returns one collection for that outer item.
Other arrangements, such as multiple internal `Iterate` nodes or an independent external `Iterate` feeding a `For` body,
-are not supported.
+are not supported as user-facing workflow shapes. The backend has a bounded
+two-branch execution-planner case for an internal body-mediated fan-in, but
+that implementation detail does not expand the supported workflow contract.
## Nested For Loops
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index b83a3eacdc..98adf6f8d5 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -25,9 +25,19 @@ consumers from `Collect.collection`, is planned by a private graph-state planner
expansion, iteration paths, downstream admission, and explicit empty-stream barrier without calling the legacy
materializer. The exact fresh two-source/two-`Iterate`/shared-`Collect.item` and exact fresh three-source/three-`Iterate`/
shared-`Collect.item` fan-in shapes also use the planner for independent stream expansions, closure gating, and
-deterministic source-ordered hydration. Fan-in with four or more branches, nested or input-driven iterators, and all
-mixed control flow retain materializer copy expansion, grouping, and empty-source handling on the legacy compatibility
-route.
+deterministic source-ordered hydration. The exact fresh two-branch body-mediated shape
+`source_a -> Iterate_a -> body_a -> Collect.item` plus
+`source_b -> Iterate_b -> body_b -> Collect.item` uses the same planner: source IDs
+are ordered lexically, each branch preserves its item order, and `Collect` runs
+only after both streams close, including explicit empty closes. This is a
+private bounded planner case: exactly seven nodes and six ordinary edges—two
+inputless ordinary sources, two `Iterate` nodes, two ordinary bodies, and one
+`Collect`; it has no
+`Collect.collection` input or downstream/extra topology. It is not a change to
+the public workflow contract.
+Three or more body-mediated branches, fan-in with four or more direct branches,
+nested or input-driven iterators, and all mixed control flow retain materializer
+copy expansion, grouping, and empty-source handling on the legacy compatibility route.
A fresh graph with exactly one static, non-empty `For`/`ForReturn` pair and ordinary body nodes also uses the generic
adapter. It projects readiness and invokes the graph-state continuation boundary, which selects the next iteration or
finalizes the aggregate without exposing a successor node ID to the generic scheduler. The materializer still owns
@@ -163,8 +173,9 @@ one ordinary preparation node from `For.item` into `Iterate.collection`, one ord
the `Collect.collection` output into the linked `ForReturn`, and one final outer-output consumer. Each outer iteration,
including an empty inner collection, remains isolated by its frame path. `Iterate` also records non-empty item streams through the generic effect ledger;
the materializer remains authoritative for fallback expansion, iteration paths, collector grouping, and
-empty-source compatibility handling. The exact fresh four-node body shape and exact two- or three-stream fan-in shapes
-use the private planner for those responsibilities; four or more streams remain compatibility-owned. Direct `Collect.item`
+empty-source compatibility handling. The exact fresh four-node body shape, exact two- or three-stream fan-in shapes,
+and exact two-branch body-mediated fan-in use the private planner for those responsibilities; three or more
+body-mediated branches and four or more direct streams remain compatibility-owned. Direct `Collect.item`
consumers now use the closed stream ledger when available;
the full Iterate/Collect compatibility matrix covers empty, nested, fan-in, partial rehydration, failure, cancellation,
and retry behavior. This evidence does not remove the materializer or queue adapters.
@@ -259,8 +270,9 @@ control-flow invocation on this seam: each non-empty prepared copy emits one ord
index, and the final copy emits one `close_stream` effect. Direct Iterate/Collect-only graphs now run through the
generic scheduler adapter; its completion maps these results/effects to the existing frame-scoped iteration-stream
identity, so legacy output mirroring is idempotent. The exact fresh four-node source/Iterate/body/Collect shape,
-its ordinary downstream consumers, and the exact two- or three-stream fan-in shapes use the private planner described
-above; four or more streams and other fallback shapes still let the
+its ordinary downstream consumers, the exact two- or three-stream fan-in shapes,
+and the exact two-branch body-mediated fan-in use the private planner described
+above; broader body-mediated fan-in, four or more streams, and other fallback shapes still let the
materializer create
prepared copies, derive iteration paths, group collector inputs, and record the explicit close for an empty source.
For a direct `Iterate.item` edge, the scheduler defers `CollectInvocation` while its canonical stream is open, and
@@ -308,8 +320,9 @@ frame-scoped continuation effects and generic readiness/continuation
projection.
Direct `Iterate`/`Collect`-only graphs use the generic scheduler adapter for
readiness and completion. The exact fresh four-node source/Iterate/body/Collect
-shape, its ordinary downstream-consumer extensions, and the exact two- or three-stream
-fan-in shapes use the private planner for expansion and empty-stream closure; four or more streams, workflow-call
+shape, its ordinary downstream-consumer extensions, the exact two- or three-stream
+fan-in shapes, and the exact two-branch body-mediated fan-in use the private planner
+for expansion and empty-stream closure; broader body-mediated fan-in, four or more streams, workflow-call
invocations, unsupported loop shapes, and mixed control-flow graphs remain on
compatibility paths. `ForInvocation` and
`ForReturnInvocation` now declare one validated, frame-scoped `continuation`
@@ -578,8 +591,9 @@ In normal execution, all runtime expansion occurs in `execution_graph` with trac
with a contiguous sequence beginning at zero, and closes its canonical
source/parent-path stream on the final copy. Exact output mirroring is
idempotent. The private planner closes empty streams for the exact fresh
- source/Iterate/body/Collect and exact two- or three-stream fan-in shapes; four or more
- streams and other fallback shapes retain materializer compatibility ownership.
+ source/Iterate/body/Collect, exact two- or three-stream fan-in, and exact
+ two-branch body-mediated fan-in shapes; broader body-mediated fan-in, four or
+ more streams, and other fallback shapes retain materializer compatibility ownership.
- Collectors wait for available direct Iterate streams to close, then aggregate
their ledger values in stream order and may also merge incoming `collection`
inputs during runtime hydration. A missing ledger remains a legacy snapshot
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 83186adc49..fd89b36ed7 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -133,6 +133,12 @@ class _DirectIterateCollectFanIn:
collector_id: str
+@dataclass(frozen=True)
+class _BodyIterateCollectFanIn:
+ branches: tuple[tuple[str, str, str], ...]
+ collector_id: str
+
+
@dataclass(frozen=True)
class _SupportedNestedIterateBody:
body_path_nodes: set[str]
@@ -2568,13 +2574,25 @@ class _ExecutionRuntime:
def _sort_collect_input_edges(self, input_edges: list[Edge], field_name: str) -> list[Edge]:
matching_edges = [edge for edge in input_edges if edge.destination.field == field_name]
- if isinstance(self._state._get_direct_iterate_collect_nodes(), _DirectIterateCollectFanIn):
+ fan_in = self._state._get_direct_iterate_collect_nodes()
+ if isinstance(fan_in, _DirectIterateCollectFanIn):
matching_edges.sort(
key=lambda edge: (
self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id),
self.get_iteration_path(edge.source.node_id),
)
)
+ elif isinstance(fan_in, _BodyIterateCollectFanIn):
+ body_source_ids = {body_id: source_id for source_id, _iterate_id, body_id in fan_in.branches}
+ matching_edges.sort(
+ key=lambda edge: (
+ body_source_ids.get(
+ self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id),
+ self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id),
+ ),
+ self.get_iteration_path(edge.source.node_id),
+ )
+ )
else:
matching_edges.sort(key=lambda edge: (self.get_iteration_path(edge.source.node_id), edge.source.node_id))
return matching_edges
@@ -2599,13 +2617,24 @@ class _ExecutionRuntime:
output_collection.extend(source_value)
else:
output_collection.append(source_value)
- stable_direct_fan_in = isinstance(self._state._get_direct_iterate_collect_nodes(), _DirectIterateCollectFanIn)
+ fan_in = self._state._get_direct_iterate_collect_nodes()
+ stable_direct_fan_in = isinstance(fan_in, _DirectIterateCollectFanIn)
+ stable_body_fan_in = isinstance(fan_in, _BodyIterateCollectFanIn)
+ body_source_ids = (
+ {body_id: source_id for source_id, _iterate_id, body_id in fan_in.branches} if stable_body_fan_in else {}
+ )
item_values: list[tuple[Any, ...]] = []
consumed_streams: set[str] = set()
for edge in item_edges:
source_node_id = self._state.prepared_source_mapping.get(edge.source.node_id, edge.source.node_id)
- item_source_id = source_node_id if stable_direct_fan_in else ""
- item_exec_id = "" if stable_direct_fan_in else edge.source.node_id
+ item_source_id = (
+ source_node_id
+ if stable_direct_fan_in
+ else body_source_ids.get(source_node_id, "")
+ if stable_body_fan_in
+ else ""
+ )
+ item_exec_id = "" if stable_direct_fan_in or stable_body_fan_in else edge.source.node_id
stream_info = self._state._stream_for_iterate_edge(edge)
if stream_info is None:
item_values.append(
@@ -2638,7 +2667,7 @@ class _ExecutionRuntime:
(item_source_id, (*parent_path, sequence), item_exec_id, copydeep(value))
for sequence, value in enumerate(stream.values)
)
- if stable_direct_fan_in:
+ if stable_direct_fan_in or stable_body_fan_in:
item_values.sort(key=lambda item: (item[0], item[1]))
else:
item_values.sort(key=lambda item: (item[1], item[2]))
@@ -5458,9 +5487,13 @@ class GraphExecutionState(BaseModel):
"""Require any available Iterate streams to close before Collect is scheduled."""
collector_source_id = self.prepared_source_mapping.get(exec_node_id)
- direct_fan_in = self._get_direct_iterate_collect_nodes() if collector_source_id is not None else None
- if isinstance(direct_fan_in, _DirectIterateCollectFanIn) and collector_source_id == direct_fan_in.collector_id:
- for _source_id, iterator_id in direct_fan_in.branches:
+ fan_in = self._get_direct_iterate_collect_nodes() if collector_source_id is not None else None
+ if (
+ isinstance(fan_in, (_DirectIterateCollectFanIn, _BodyIterateCollectFanIn))
+ and collector_source_id == fan_in.collector_id
+ ):
+ for branch in fan_in.branches:
+ iterator_id = branch[1]
stream = self._generic_runtime().streams.get(self._iteration_stream_id(iterator_id, ()))
if stream is None or not stream.closed:
return False
@@ -6776,10 +6809,93 @@ class GraphExecutionState(BaseModel):
branches.sort(key=lambda branch: branch[0])
return _DirectIterateCollectFanIn(branches=tuple(branches), collector_id=collector_id)
+ def _get_body_iterate_collect_fan_in(
+ self, iterator_ids: list[str], collector_id: str
+ ) -> Optional[_BodyIterateCollectFanIn]:
+ if len(iterator_ids) != 2 or len(self.graph.nodes) != 7 or len(self.graph.edges) != 6:
+ return None
+
+ item_edges = self.graph._get_input_edges(collector_id, ITEM_FIELD)
+ if len(item_edges) != 2 or self.graph._get_input_edges(collector_id, COLLECTION_FIELD):
+ return None
+ if any(edge.destination.field != ITEM_FIELD for edge in item_edges):
+ return None
+
+ item_edges_by_body = {edge.source.node_id: edge for edge in item_edges}
+ branches: list[tuple[str, str, str]] = []
+ for iterator_id in iterator_ids:
+ collection_edges = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)
+ if len(collection_edges) != 1:
+ return None
+ collection_edge = collection_edges[0]
+ if collection_edge.destination.node_id != iterator_id or collection_edge.source.field != COLLECTION_FIELD:
+ return None
+
+ source_id = collection_edge.source.node_id
+ source = self.graph.get_node(source_id)
+ if isinstance(
+ source,
+ (
+ CallSavedWorkflowInvocation,
+ ForInvocation,
+ ForReturnInvocation,
+ IfInvocation,
+ IterateInvocation,
+ CollectInvocation,
+ ),
+ ):
+ return None
+ if self.graph._get_input_edges(source_id) or self.graph._get_output_edges(source_id) != [collection_edge]:
+ return None
+
+ iterator_item_edges = self.graph._get_output_edges(iterator_id, ITEM_FIELD)
+ if len(iterator_item_edges) != 1 or iterator_item_edges[0].source.node_id != iterator_id:
+ return None
+ if self.graph._get_output_edges(iterator_id) != iterator_item_edges:
+ return None
+
+ body_edge = iterator_item_edges[0]
+ if body_edge.source.field != ITEM_FIELD:
+ return None
+ body_id = body_edge.destination.node_id
+ if body_id in {source_id, iterator_id, collector_id} or body_id not in item_edges_by_body:
+ return None
+ body = self.graph.get_node(body_id)
+ if isinstance(
+ body,
+ (
+ CallSavedWorkflowInvocation,
+ ForInvocation,
+ ForReturnInvocation,
+ IfInvocation,
+ IterateInvocation,
+ CollectInvocation,
+ ),
+ ):
+ return None
+ body_input_edges = self.graph._get_input_edges(body_id)
+ if len(body_input_edges) != 1 or body_input_edges[0] != body_edge:
+ return None
+
+ collect_item_edge = item_edges_by_body[body_id]
+ if self.graph._get_output_edges(body_id) != [collect_item_edge]:
+ return None
+ branches.append((source_id, iterator_id, body_id))
+
+ if len({source_id for source_id, _iterator_id, _body_id in branches}) != 2:
+ return None
+ if len({iterator_id for _source_id, iterator_id, _body_id in branches}) != 2:
+ return None
+ if len({body_id for _source_id, _iterator_id, body_id in branches}) != 2:
+ return None
+
+ branches.sort(key=lambda branch: branch[0])
+ return _BodyIterateCollectFanIn(branches=tuple(branches), collector_id=collector_id)
+
def _get_direct_iterate_collect_nodes(
self,
- ) -> Optional[tuple[str, str, str, str, tuple[str, ...]] | _DirectIterateCollectFanIn]:
- """Return direct planner nodes, including ordinary downstream consumers."""
+ ) -> Optional[tuple[str, str, str, str, tuple[str, ...]] | _DirectIterateCollectFanIn | _BodyIterateCollectFanIn]:
+ """Return fresh direct/body planner nodes, including ordinary downstream consumers."""
if (
self._legacy_snapshot_loaded
@@ -6791,6 +6907,10 @@ class GraphExecutionState(BaseModel):
iterator_ids = [node_id for node_id, node in self.graph.nodes.items() if isinstance(node, IterateInvocation)]
collector_ids = [node_id for node_id, node in self.graph.nodes.items() if isinstance(node, CollectInvocation)]
if len(iterator_ids) in {2, 3} and len(collector_ids) == 1:
+ if len(iterator_ids) == 2:
+ body_fan_in = self._get_body_iterate_collect_fan_in(iterator_ids, collector_ids[0])
+ if body_fan_in is not None:
+ return body_fan_in
return self._get_direct_iterate_collect_fan_in(iterator_ids, collector_ids[0])
if len(iterator_ids) != 1 or len(collector_ids) != 1:
return None
@@ -6964,6 +7084,83 @@ class GraphExecutionState(BaseModel):
attached_collector_edges = self._attach_direct_execution_edges(collector_node.id, collector_edges)
self._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
+ def _prepare_body_iterate_collect_fan_in_unchecked(self, fan_in: _BodyIterateCollectFanIn) -> None:
+ source_exec_ids: dict[str, str] = {}
+ for source_id, _iterator_id, _body_id in fan_in.branches:
+ if source_id not in self.source_prepared_mapping:
+ source_node = self._create_direct_execution_node_copy(source_id)
+ self._initialize_direct_execution_node(source_node.id, ())
+ if source_id in self.executed:
+ source_exec_ids[source_id] = sorted(self.source_prepared_mapping[source_id])[0]
+
+ if len(source_exec_ids) != len(fan_in.branches):
+ return
+ if fan_in.collector_id in self.source_prepared_mapping:
+ return
+
+ collections: dict[str, list[Any]] = {}
+ for source_id, iterator_id, _body_id in fan_in.branches:
+ collection_edge = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
+ collection = getattr(self.results[source_exec_ids[source_id]], collection_edge.source.field)
+ if not isinstance(collection, list):
+ raise ValueError("Body Iterate collection source must produce a list")
+ collections[source_id] = collection
+
+ collector_item_edges = {
+ edge.source.node_id: edge for edge in self.graph._get_input_edges(fan_in.collector_id, ITEM_FIELD)
+ }
+ for source_id, iterator_id, body_id in fan_in.branches:
+ collection_edge = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]
+ body_input_edge = self.graph._get_input_edges(body_id)[0]
+ collect_item_edge = collector_item_edges[body_id]
+ source_exec_id = source_exec_ids[source_id]
+ collection = collections[source_id]
+ for index in range(len(collection)):
+ iterator_node = self._create_direct_execution_node_copy(iterator_id, index, (index,))
+ attached_iterator_edges = self._attach_direct_execution_edges(
+ iterator_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=source_exec_id, field=collection_edge.source.field),
+ destination=EdgeConnection(node_id="", field=collection_edge.destination.field),
+ )
+ ],
+ )
+ self._initialize_direct_execution_node(iterator_node.id, attached_iterator_edges)
+
+ body_node = self._create_direct_execution_node_copy(body_id, iteration_path=(index,))
+ attached_body_edges = self._attach_direct_execution_edges(
+ body_node.id,
+ [
+ Edge(
+ source=EdgeConnection(node_id=iterator_node.id, field=body_input_edge.source.field),
+ destination=EdgeConnection(node_id="", field=body_input_edge.destination.field),
+ )
+ ],
+ )
+ self._initialize_direct_execution_node(body_node.id, attached_body_edges)
+
+ if not collection:
+ self._mark_direct_source_empty(iterator_id)
+ self._mark_direct_source_empty(body_id)
+
+ collector_node = self._create_direct_execution_node_copy(fan_in.collector_id, iteration_path=())
+ collector_edges: list[Edge] = []
+ for _source_id, _iterator_id, body_id in fan_in.branches:
+ collect_item_edge = collector_item_edges[body_id]
+ for body_exec_id in sorted(
+ self.source_prepared_mapping.get(body_id, set()),
+ key=lambda exec_id: self._get_iteration_path(exec_id),
+ ):
+ collector_edges.append(
+ Edge(
+ source=EdgeConnection(node_id=body_exec_id, field=collect_item_edge.source.field),
+ destination=EdgeConnection(node_id="", field=collect_item_edge.destination.field),
+ )
+ )
+ attached_collector_edges = self._attach_direct_execution_edges(collector_node.id, collector_edges)
+ self._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
+
def _prepare_direct_iterate_collect(self) -> None:
"""Expand the fresh direct stream shape atomically, without the legacy materializer."""
@@ -6991,6 +7188,9 @@ class GraphExecutionState(BaseModel):
node_ids = self._get_direct_iterate_collect_nodes()
if node_ids is None:
return
+ if isinstance(node_ids, _BodyIterateCollectFanIn):
+ self._prepare_body_iterate_collect_fan_in_unchecked(node_ids)
+ return
if isinstance(node_ids, _DirectIterateCollectFanIn):
self._prepare_direct_iterate_collect_fan_in_unchecked(node_ids)
return
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 69d71638f7..11e48cb562 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -332,6 +332,34 @@ def _direct_iterate_fan_in_graph(*, left: list[Any], right: list[Any]) -> Graph:
return graph
+def _body_iterate_fan_in_graph(*, branches: tuple[tuple[str, str, str, list[Any]], ...]) -> Graph:
+ graph = Graph()
+ graph.add_node(CollectInvocation(id="collect"))
+ for source_id, iterate_id, body_id, values in branches:
+ graph.add_node(CollectionConcatInvocation(id=source_id, first=values))
+ graph.add_node(IterateInvocation(id=iterate_id))
+ graph.add_node(AnyTypeTestInvocation(id=body_id))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id=source_id, field="collection"),
+ destination=EdgeConnection(node_id=iterate_id, field="collection"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id=iterate_id, field="item"),
+ destination=EdgeConnection(node_id=body_id, field="value"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id=body_id, field="value"),
+ destination=EdgeConnection(node_id="collect", field="item"),
+ )
+ )
+ return graph
+
+
def _direct_iterate_fan_in_graph_with_branches(
branches: tuple[tuple[str, str, list[Any]], ...],
) -> Graph:
@@ -742,19 +770,125 @@ def _effect_ledger_projection(state: GraphExecutionState) -> tuple[Any, ...]:
return tuple(
sorted(
(
- next(
- (
- state.prepared_source_mapping.get(exec_node_id, exec_node_id)
- for exec_node_id, reference in state.execution_refs.items()
- if reference.reference_id == reference_id
+ (
+ next(
+ (
+ state.prepared_source_mapping.get(exec_node_id, exec_node_id)
+ for exec_node_id, reference in state.execution_refs.items()
+ if reference.reference_id == reference_id
+ ),
+ reference_id,
),
- reference_id,
- ),
- normalized(effects),
+ normalized(effects),
+ )
+ for reference_id, effects in state.execution_effects.items()
+ ),
+ key=repr,
+ )
+ )
+
+
+def _execution_token_projection(state: GraphExecutionState) -> tuple[Any, ...]:
+ """Project durable data tokens without generated execution identities."""
+ return tuple(
+ sorted(
+ (
+ (
+ state.prepared_source_mapping.get(token.owner_node_id, token.owner_node_id),
+ token.port,
+ _stable_json(token.value),
+ token.token_kind,
+ token.sequence,
+ tuple(token.frame.iteration_path),
+ token.frame.workflow_call_depth,
+ )
+ for token in state.execution_tokens.values()
+ ),
+ key=repr,
+ )
+ )
+
+
+def _stable_json(value: Any) -> str:
+ def jsonable(item: Any) -> Any:
+ if hasattr(item, "model_dump"):
+ return jsonable(item.model_dump(mode="json", warnings=False))
+ if isinstance(item, dict):
+ return {str(key): jsonable(value) for key, value in item.items()}
+ if isinstance(item, (list, tuple)):
+ return [jsonable(value) for value in item]
+ if isinstance(item, set):
+ return sorted((jsonable(value) for value in item), key=repr)
+ return item
+
+ return json.dumps(jsonable(value), sort_keys=True, default=str)
+
+
+def _body_fan_in_graph_projection(state: GraphExecutionState) -> tuple[Any, ...]:
+ nodes = tuple(sorted((node_id, _stable_json(node)) for node_id, node in state.execution_graph.nodes.items()))
+ edges = tuple(
+ sorted(
+ (
+ edge.source.node_id,
+ edge.source.field,
+ edge.destination.node_id,
+ edge.destination.field,
+ edge.type,
)
- for reference_id, effects in state.execution_effects.items()
+ for edge in state.execution_graph.edges
)
)
+ return nodes, edges
+
+
+def _body_fan_in_durable_projection(state: GraphExecutionState) -> tuple[Any, ...]:
+ """Exact pre/post transaction projection; generated IDs intentionally remain exact."""
+ return (
+ tuple(sorted(state.prepared_source_mapping.items())),
+ tuple(
+ sorted(
+ (source_id, tuple(sorted(exec_ids))) for source_id, exec_ids in state.source_prepared_mapping.items()
+ )
+ ),
+ tuple(sorted(state.prepared_iteration_paths.items())),
+ tuple(sorted(state.finalized_loop_contexts)),
+ _body_fan_in_graph_projection(state),
+ tuple(sorted(state.indegree.items())),
+ tuple(sorted(state.executed)),
+ tuple(state.executed_history),
+ tuple(sorted((exec_node_id, _stable_json(output)) for exec_node_id, output in state.results.items())),
+ tuple(sorted(state.errors.items())),
+ tuple(
+ sorted((exec_node_id, _stable_json(reference)) for exec_node_id, reference in state.execution_refs.items())
+ ),
+ tuple(sorted((token_id, _stable_json(token)) for token_id, token in state.execution_tokens.items())),
+ tuple(
+ sorted((reference_id, _stable_json(effects)) for reference_id, effects in state.execution_effects.items())
+ ),
+ )
+
+
+def _body_fan_in_runtime_projection(state: GraphExecutionState) -> tuple[Any, ...]:
+ metadata = tuple(
+ sorted(
+ (
+ exec_node_id,
+ metadata.source_node_id,
+ metadata.iteration_path,
+ metadata.state,
+ )
+ for exec_node_id, metadata in state._prepared_exec_metadata.items()
+ )
+ )
+ ready_queues = tuple(sorted((class_name, tuple(queue)) for class_name, queue in state._ready_queues.items()))
+ return (
+ _direct_iterate_fan_in_stream_projection(state),
+ metadata,
+ ready_queues,
+ tuple(sorted(state._ready_node_ids)),
+ state._active_class,
+ tuple(state.ready_order),
+ )
def _direct_iterate_fan_in_stream_projection(state: GraphExecutionState) -> tuple[Any, ...]:
@@ -1896,6 +2030,502 @@ def test_direct_iterate_four_fan_in_stays_on_compatibility_fallback() -> None:
assert compatibility_state.is_complete()
+def test_body_iterate_fan_in_fresh_execution_owns_exact_two_branch_shape() -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("z_source", "z_iterate", "z_body", ["z", None, "z"]),
+ ("a_source", "a_iterate", "a_body", ["a", None, "a"]),
+ )
+ )
+ assert len(graph.nodes) == 7
+ assert len(graph.edges) == 6
+ state = GraphExecutionState(graph=graph)
+ fan_in = state._get_direct_iterate_collect_nodes()
+ assert isinstance(fan_in, graph_module._BodyIterateCollectFanIn)
+ assert fan_in.branches == (
+ ("a_source", "a_iterate", "a_body"),
+ ("z_source", "z_iterate", "z_body"),
+ )
+
+ with (
+ patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("body fan-in must not use materializer.prepare"),
+ ) as prepare,
+ patch.object(
+ graph_module._ExecutionMaterializer,
+ "_get_collect_iteration_mapping_groups",
+ side_effect=AssertionError("body fan-in must not group collector inputs"),
+ ) as group_collector_inputs,
+ ):
+ trace, state = _run_graph(state)
+
+ assert trace.count("a_source") == trace.count("z_source") == 1
+ assert trace.count("a_iterate") == 3
+ assert trace.count("z_iterate") == 3
+ assert trace.count("a_body") == 3
+ assert trace.count("z_body") == 3
+ assert trace.count("collect") == 1
+ assert _source_output(state, "collect").collection == ["a", None, "a", "z", None, "z"]
+ assert state.is_complete()
+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)
+ prepare.assert_not_called()
+ group_collector_inputs.assert_not_called()
+
+
+def test_body_iterate_fan_in_orders_by_source_id_not_body_id() -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("z_source", "z_iterate", "a_body", ["z-0", "z-1"]),
+ ("a_source", "a_iterate", "z_body", ["a-0", "a-1"]),
+ )
+ )
+ state = GraphExecutionState(graph=graph)
+ fan_in = state._get_direct_iterate_collect_nodes()
+ assert isinstance(fan_in, graph_module._BodyIterateCollectFanIn)
+ assert fan_in.branches == (
+ ("a_source", "a_iterate", "z_body"),
+ ("z_source", "z_iterate", "a_body"),
+ )
+
+ trace, state = _run_graph_with_effects(state)
+
+ assert trace[-1] == "collect"
+ assert _source_output(state, "collect").collection == ["a-0", "a-1", "z-0", "z-1"]
+ assert state.is_complete()
+
+
+ ("left", "right", "expected"),
+ [
+ ([], ["right", None], ["right", None]),
+ (["left", None], [], ["left", None]),
+ ([], [], []),
+ ],
+ ids=["left-empty", "right-empty", "both-empty"],
+)
+def test_body_iterate_fan_in_closes_empty_branches(left: list[Any], right: list[Any], expected: list[Any]) -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("right_source", "right_iterate", "right_body", right),
+ ("left_source", "left_iterate", "left_body", left),
+ )
+ )
+ trace, state = _run_graph(GraphExecutionState(graph=graph))
+
+ assert trace.count("collect") == 1
+ assert _source_output(state, "collect").collection == expected
+ streams = {
+ stream.owner_id: stream
+ for stream in state._generic_runtime().streams.values()
+ if stream.owner_id in {"left_iterate", "right_iterate"}
+ }
+ assert set(streams) == {"left_iterate", "right_iterate"}
+ assert all(stream.closed for stream in streams.values())
+ assert state.is_complete()
+
+
[email protected]("force_compatibility_scheduler", [False, True])
+def test_body_iterate_fan_in_partial_dump_load_preserves_streams_and_effects(
+ force_compatibility_scheduler: bool,
+) -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("right_source", "right_iterate", "right_body", ["right-0", "right-1"]),
+ ("left_source", "left_iterate", "left_body", ["left-0", "left-1"]),
+ )
+ )
+ expected_trace, expected_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler
+ )
+ partial_trace, partial_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph),
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ stop_after=3,
+ )
+
+ assert "collect" not in partial_trace
+ if not force_compatibility_scheduler:
+ assert (
+ not partial_state._generic_runtime().streams[partial_state._iteration_stream_id("left_iterate", ())].closed
+ )
+ restored = load_execution_state(dump_execution_state(partial_state))
+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ restored, execution_ids=set(partial_state.execution_refs)
+ ) == _direct_iterate_fan_in_execution_ref_projection(partial_state)
+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)
+ if force_compatibility_scheduler:
+ _restore_compatibility_scheduler(restored)
+ resumed_trace, resumed_state = _run_graph_with_effects(
+ restored, force_compatibility_scheduler=force_compatibility_scheduler
+ )
+
+ assert partial_trace + resumed_trace == expected_trace
+ assert _source_output(resumed_state, "collect").collection == [
+ "left-0",
+ "left-1",
+ "right-0",
+ "right-1",
+ ]
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(
+ expected_state
+ )
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ resumed_state
+ ) == _direct_iterate_fan_in_execution_ref_projection(expected_state)
+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)
+ assert resumed_state.is_complete()
+
+
[email protected]("force_compatibility_scheduler", [False, True])
+def test_body_iterate_fan_in_source_prepared_dump_load_resumes(
+ force_compatibility_scheduler: bool,
+) -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("right_source", "right_iterate", "right_body", ["right-0", "right-1"]),
+ ("left_source", "left_iterate", "left_body", ["left-0", "left-1"]),
+ )
+ )
+ expected_trace, expected_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler
+ )
+ partial_trace, partial_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph),
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ stop_after=2,
+ )
+
+ assert partial_trace == expected_trace[:2]
+ assert set(partial_trace) == {"left_source", "right_source"}
+ assert set(partial_state.source_prepared_mapping) == {"left_source", "right_source"}
+ assert "collect" not in partial_state.source_prepared_mapping
+ assert not partial_state._generic_runtime().streams
+ checkpoint = dump_execution_state(partial_state)
+ restored = load_execution_state(checkpoint)
+ assert _state_projection(restored) == _state_projection(partial_state)
+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ restored, execution_ids=set(partial_state.execution_refs)
+ ) == _direct_iterate_fan_in_execution_ref_projection(partial_state)
+ assert _execution_token_projection(restored) == _execution_token_projection(partial_state)
+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)
+ if force_compatibility_scheduler:
+ _restore_compatibility_scheduler(restored)
+
+ resumed_trace, resumed_state = _run_graph_with_effects(
+ restored, force_compatibility_scheduler=force_compatibility_scheduler
+ )
+
+ assert partial_trace + resumed_trace == expected_trace
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(
+ expected_state
+ )
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ resumed_state
+ ) == _direct_iterate_fan_in_execution_ref_projection(expected_state)
+ assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)
+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)
+ assert resumed_state.is_complete()
+
+
+def test_body_iterate_fan_in_partial_dump_load_after_one_stream_closes() -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("right_source", "right_iterate", "right_body", ["right-0", "right-1"]),
+ ("left_source", "left_iterate", "left_body", ["left-0"]),
+ )
+ )
+ expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph))
+ partial_trace, partial_state = _run_graph_with_effects(GraphExecutionState(graph=graph), stop_after=3)
+
+ assert partial_trace == ["left_source", "right_source", "left_iterate"]
+ streams = partial_state._generic_runtime().streams
+ assert streams[partial_state._iteration_stream_id("left_iterate", ())].closed
+ right_stream = streams.get(partial_state._iteration_stream_id("right_iterate", ()))
+ assert right_stream is None or not right_stream.closed
+ assert "collect" not in partial_trace
+
+ restored = load_execution_state(dump_execution_state(partial_state))
+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(partial_state)
+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)
+ resumed_trace, resumed_state = _run_graph_with_effects(restored)
+
+ assert partial_trace + resumed_trace == expected_trace
+ assert _source_output(resumed_state, "collect").collection == ["left-0", "right-0", "right-1"]
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(
+ expected_state
+ )
+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)
+ assert resumed_state.is_complete()
+
+
+ ("left", "right", "expected"),
+ [
+ (["left", None, "left"], ["right", None], ["left", None, "left", "right", None]),
+ ([], ["right", None], ["right", None]),
+ ([], [], []),
+ ],
+ ids=["ordered-none-duplicates", "mixed-empty", "all-empty"],
+)
+def test_body_iterate_fan_in_matches_forced_compatibility_scheduler(
+ left: list[Any], right: list[Any], expected: list[Any]
+) -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("left_source", "left_iterate", "left_body", left),
+ ("right_source", "right_iterate", "right_body", right),
+ )
+ )
+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph))
+ compatibility_trace, compatibility_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True
+ )
+
+ assert generic_trace == compatibility_trace
+ assert _source_output(generic_state, "collect").collection == expected
+ assert (
+ _source_output(generic_state, "collect").collection == _source_output(compatibility_state, "collect").collection
+ )
+ if left or right:
+ assert _state_projection(generic_state) == _state_projection(compatibility_state)
+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(
+ compatibility_state
+ )
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ generic_state
+ ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)
+ assert _execution_token_projection(generic_state) == _execution_token_projection(compatibility_state)
+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)
+ assert _execution_edge_projection(generic_state) == _execution_edge_projection(compatibility_state)
+ assert generic_state.is_complete()
+ assert compatibility_state.is_complete()
+
+
[email protected]("force_compatibility_scheduler", [False, True])
[email protected]("fail_source_id", ["right_source", "right_iterate", "right_body"])
+def test_body_iterate_fan_in_failure_blocks_collect_and_persists(
+ force_compatibility_scheduler: bool, fail_source_id: str
+) -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("left_source", "left_iterate", "left_body", ["left"]),
+ ("right_source", "right_iterate", "right_body", ["right"]),
+ )
+ )
+ trace, state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph),
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ fail_source_id=fail_source_id,
+ )
+
+ assert trace[-1] == fail_source_id
+ assert "collect" not in trace
+ assert state.has_error()
+ assert state.is_complete()
+ assert state.next() is None
+ assert tuple(
+ sorted(
+ (state.prepared_source_mapping.get(execution_id, execution_id), message)
+ for execution_id, message in state.errors.items()
+ )
+ ) == ((fail_source_id, "injected failure"),)
+ restored = load_execution_state(dump_execution_state(state))
+ assert _state_projection(restored) == _state_projection(state)
+ assert _execution_edge_projection(restored) == _execution_edge_projection(state)
+ assert _direct_iterate_fan_in_stream_projection(restored) == _direct_iterate_fan_in_stream_projection(state)
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ restored, execution_ids=set(state.execution_refs)
+ ) == _direct_iterate_fan_in_execution_ref_projection(state)
+ assert _execution_token_projection(restored) == _execution_token_projection(state)
+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)
+ assert restored.has_error()
+ assert tuple(
+ sorted(
+ (restored.prepared_source_mapping.get(execution_id, execution_id), message)
+ for execution_id, message in restored.errors.items()
+ )
+ ) == ((fail_source_id, "injected failure"),)
+ assert restored.next() is None
+ assert restored.is_complete()
+
+
[email protected]("fail_source_id", ["right_source", "right_iterate", "right_body"])
+def test_body_iterate_fan_in_failure_matches_forced_compatibility_scheduler(fail_source_id: str) -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("left_source", "left_iterate", "left_body", ["left"]),
+ ("right_source", "right_iterate", "right_body", ["right"]),
+ )
+ )
+ generic_trace, generic_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph), fail_source_id=fail_source_id
+ )
+ compatibility_trace, compatibility_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph),
+ force_compatibility_scheduler=True,
+ fail_source_id=fail_source_id,
+ )
+
+ assert generic_trace == compatibility_trace
+ assert generic_state.has_error() == compatibility_state.has_error()
+ assert generic_state.is_complete() == compatibility_state.is_complete()
+ assert {
+ generic_state.prepared_source_mapping.get(execution_id, execution_id): message
+ for execution_id, message in generic_state.errors.items()
+ } == {
+ compatibility_state.prepared_source_mapping.get(execution_id, execution_id): message
+ for execution_id, message in compatibility_state.errors.items()
+ }
+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(
+ compatibility_state
+ )
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ generic_state
+ ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)
+ assert _execution_token_projection(generic_state) == _execution_token_projection(compatibility_state)
+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)
+ for state in (generic_state, compatibility_state):
+ assert state.has_error()
+ assert "collect" not in {
+ state.prepared_source_mapping.get(execution_id, execution_id) for execution_id in state.executed
+ }
+ assert state.is_complete()
+
+
+def test_body_iterate_fan_in_rolls_back_mid_expansion_and_retries(monkeypatch: pytest.MonkeyPatch) -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("left_source", "left_iterate", "left_body", ["left"]),
+ ("right_source", "right_iterate", "right_body", ["right"]),
+ )
+ )
+ state = GraphExecutionState(graph=graph)
+ _partial_trace, state = _run_graph_with_effects(state, stop_after=2)
+ before_failure_durable = _body_fan_in_durable_projection(state)
+ before_failure_runtime = _body_fan_in_runtime_projection(state)
+
+ original_create = GraphExecutionState._create_direct_execution_node_copy
+
+ def fail_at_right_body(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):
+ if source_node_id == "right_body":
+ raise RuntimeError("injected body fan-in planner failure")
+ return original_create(self, source_node_id, *args, **kwargs)
+
+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_right_body)
+ with pytest.raises(RuntimeError, match="injected body fan-in planner failure"):
+ state.next()
+
+ assert _body_fan_in_durable_projection(state) == before_failure_durable
+ assert _body_fan_in_runtime_projection(state) == before_failure_runtime
+
+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)
+ trace, state = _run_graph_with_effects(state)
+ expected_trace, expected_state = _run_graph_with_effects(
+ GraphExecutionState(
+ graph=_body_iterate_fan_in_graph(
+ branches=(
+ ("left_source", "left_iterate", "left_body", ["left"]),
+ ("right_source", "right_iterate", "right_body", ["right"]),
+ )
+ )
+ )
+ )
+
+ assert _partial_trace + trace == expected_trace
+ assert trace == ["left_iterate", "right_iterate", "left_body", "right_body", "collect"]
+ assert _source_output(state, "collect").collection == ["left", "right"]
+ assert _state_projection(state) == _state_projection(expected_state)
+ assert _direct_iterate_fan_in_stream_projection(state) == _direct_iterate_fan_in_stream_projection(expected_state)
+ assert _direct_iterate_fan_in_execution_ref_projection(state) == _direct_iterate_fan_in_execution_ref_projection(
+ expected_state
+ )
+ assert _execution_token_projection(state) == _execution_token_projection(expected_state)
+ assert _effect_ledger_projection(state) == _effect_ledger_projection(expected_state)
+ assert state.is_complete()
+
+
+def test_body_iterate_fan_in_unsupported_topology_uses_compatibility_fallback() -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("m_source", "m_iterate", "m_body", ["m"]),
+ ("z_source", "z_iterate", "z_body", ["z"]),
+ ("a_source", "a_iterate", "a_body", ["a"]),
+ )
+ )
+ assert GraphExecutionState(graph=graph)._get_direct_iterate_collect_nodes() is None
+
+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph))
+ compatibility_trace, compatibility_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True
+ )
+
+ assert generic_trace == compatibility_trace
+ generic_collection = _source_output(generic_state, "collect").collection
+ compatibility_collection = _source_output(compatibility_state, "collect").collection
+ # Unsupported body-mediated fan-in stays on the legacy materializer. Its item ordering
+ # is not part of this bounded planner's contract, but values (including duplicates) must
+ # be retained; only the admitted two-branch planner promises lexical source ordering.
+ assert sorted(generic_collection) == sorted(compatibility_collection) == ["a", "m", "z"]
+ assert _execution_edge_projection(generic_state) == _execution_edge_projection(compatibility_state)
+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(
+ compatibility_state
+ )
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ generic_state
+ ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)
+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)
+ assert generic_state.is_complete()
+ assert compatibility_state.is_complete()
+
+
+def test_body_iterate_fan_in_downstream_topology_stays_on_compatibility_fallback() -> None:
+ graph = _body_iterate_fan_in_graph(
+ branches=(
+ ("right_source", "right_iterate", "right_body", ["right"]),
+ ("left_source", "left_iterate", "left_body", ["left"]),
+ )
+ )
+ graph.add_node(AnyTypeTestInvocation(id="after"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="collect", field="collection"),
+ destination=EdgeConnection(node_id="after", field="value"),
+ )
+ )
+
+ assert GraphExecutionState(graph=graph)._get_direct_iterate_collect_nodes() is None
+
+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph))
+ compatibility_trace, compatibility_state = _run_graph_with_effects(
+ GraphExecutionState(graph=graph), force_compatibility_scheduler=True
+ )
+
+ assert generic_trace == compatibility_trace
+ assert generic_trace[-2:] == ["collect", "after"]
+ generic_collection = _source_output(generic_state, "collect").collection
+ compatibility_collection = _source_output(compatibility_state, "collect").collection
+ assert sorted(generic_collection) == sorted(compatibility_collection) == ["left", "right"]
+ assert _source_output(generic_state, "after").value == generic_collection
+ assert _source_output(compatibility_state, "after").value == compatibility_collection
+ assert _execution_edge_projection(generic_state) == _execution_edge_projection(compatibility_state)
+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(
+ compatibility_state
+ )
+ assert _direct_iterate_fan_in_execution_ref_projection(
+ generic_state
+ ) == _direct_iterate_fan_in_execution_ref_projection(compatibility_state)
+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)
+ assert generic_state.is_complete()
+ assert compatibility_state.is_complete()
+
+
def test_direct_iterate_body_collect_fresh_execution_handles_empty_input() -> None:
state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=[]))
with (