Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(execution): plan canonical iterate body collect
JPPhotoa5c4108dff4d
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex 0b320bc972..844d273ffe 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -108,16 +108,19 @@ bounded outer-`For`/`Iterate`/`Collect` shape are now generic-routed. This additscheduling for the remaining shapes. `Iterate` records ordered item tokens ina closed `StreamBuffer`; an empty `Iterate` records anexplicit empty close. A direct `Iterate.item` consumer waits for the canonical stream to close, then `Collect` consumes-its ordered values; a missing stream falls back to materialized results for legacy snapshots. The materializer still-owns iterator expansion, iteration paths, collector grouping, collection-input hydration, and empty-source closure.+its ordered values; a missing stream falls back to materialized results for legacy snapshots. The exact fresh four-node+`literal collection source -> Iterate -> one ordinary body -> Collect` shape uses a private graph-state planner for+prepared-copy expansion, iteration paths, and the empty-stream barrier. Downstream consumers, fan-in, nested or+input-driven iterators, and mixed control flow remain on the compatibility materializer for those responsibilities.Focused compatibility coverage now proves empty, nested, fan-in, partial/rehydrated, failed, canceled, and retriedIterate/Collect sessions. This is evidence for the current adapters; it does not remove materialization or queueownership. Direct `Iterate`/`Collect`-only graphs and the exact bounded nested shape now use the generic scheduleradapter: its readiness predicate waits for the canonical stream to close, and completion mirrors Iterate outputs intothat ledger before releasing Collect. Rehydration restores the active class-drain boundary so nested stream order ispreserved across dump/load.-Materialization still owns copy expansion, iteration paths, grouping, and explicit empty closure; mixed control-flow and-queue lifecycle remain compatibility-owned. `loop_linkage` remains association metadata and never becomes a data token.+For the exact fresh four-node shape, the planner owns expansion and empty closure; materialization still owns those+responsibilities for fallback shapes. Mixed control-flow and queue lifecycle remain compatibility-owned. `loop_linkage`+remains association metadata and never becomes a data token.The supported flat-loop differential gate covers generic/compatibility parityfor successful execution, carried and replaced state, early break, empty anddiff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 5e07e026fb..b1eaa6df34 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -18,9 +18,12 @@ Legacy skipped-state metadata remains only for snapshots that already contain thanalysis remains an internal author-graph admission decision.Direct `Iterate`/`Collect` graphs that do not contain `If`, `For`, `ForReturn`, or saved-workflow control flow also usethe generic adapter. Its adapter-level readiness predicate waits for canonical Iterate streams to close, and generic-completion mirrors each Iterate result into that ledger before releasing `Collect`; materialization still owns copy-expansion, iteration paths, grouping, and explicit empty-stream closure. Mixed control-flow shapes remain on the legacy-compatibility scheduler until their differential gates are complete.+completion mirrors each Iterate result into that ledger before releasing `Collect`. The exact fresh four-node shape+`literal collection source -> Iterate -> one ordinary body -> Collect` is planned by a private graph-state planner,+which owns its prepared-copy expansion, iteration paths, and explicit empty-stream barrier without calling the legacy+materializer. The planner intentionally excludes downstream consumers, fan-in, nested or input-driven iterators, and+all mixed control flow; those shapes 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 genericadapter. It projects readiness and invokes the graph-state continuation boundary, which selects the next iteration orfinalizes the aggregate without exposing a successor node ID to the generic scheduler. The materializer still owns@@ -248,13 +251,15 @@ Activation effects are excluded from data-stream handling. `IterateInvocation` icontrol-flow invocation on this seam: each non-empty prepared copy emits one ordered `item` effect with its iterationindex, and the final copy emits one `close_stream` effect. Direct Iterate/Collect-only graphs now run through thegeneric scheduler adapter; its completion maps these results/effects to the existing frame-scoped iteration-stream-identity, so legacy output mirroring is idempotent. The materializer still creates-prepared copies, derives iteration paths, groups collector inputs, and records the explicit close for an empty source.+identity, so legacy output mirroring is idempotent. The exact fresh four-node source/Iterate/body/Collect shape uses+the private planner described above; 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, andruntime hydration consumes the closed stream in sequence order. If no stream exists, hydration retains the legacymaterialized-result fallback needed by older snapshots. This is not yet token-authoritative downstream topology or full-`Collect` migration: the materializer still owns copy expansion, iteration paths, collector grouping, collection-input-hydration, and empty-source closure; no author-time activation ports or literal successor IDs are introduced.+`Collect` migration: fallback shapes still let the materializer own copy expansion, iteration paths, collector grouping,+collection-input hydration, and empty-source closure; the exact fresh four-node source/Iterate/body/Collect shape uses+the private planner instead. No author-time activation ports or literal successor IDs are introduced.For a fresh graph with one static, non-empty flat `For`/`ForReturn` pair, the same adapter now projects ordinaryreadiness and calls the graph-state generic continuation boundary after each `ForReturn`. That boundary carries returned@@ -291,8 +296,9 @@ the supported static, non-empty flat `For`/`ForReturn` shape uses it forframe-scoped continuation effects and generic readiness/continuationprojection.Direct `Iterate`/`Collect`-only graphs use the generic scheduler adapter for-readiness and completion, while the materializer still expands copies and-groups paths. Workflow-call invocations, unsupported loop shapes, and mixed+readiness and completion. The exact fresh four-node source/Iterate/body/Collect+shape uses the private planner for expansion and empty-stream closure;+workflow-call invocations, unsupported loop shapes, and mixedcontrol-flow graphs remain on compatibility paths. `ForInvocation` and`ForReturnInvocation` now declare one validated, frame-scoped `continuation`effect per prepared invocation: `For` starts the `for` continuation with its@@ -558,8 +564,9 @@ In normal execution, all runtime expansion occurs in `execution_graph` with trac- A non-empty `IterateInvocation` emits one `item` effect per prepared copy,with a contiguous sequence beginning at zero, and closes its canonicalsource/parent-path stream on the final copy. Exact output mirroring is- idempotent; empty-source closure remains a materializer compatibility- operation.+ idempotent. The private planner closes an empty stream for the exact fresh+ source/Iterate/body/Collect shape; fallback shapes retain materializer+ compatibility ownership.- Collectors wait for available direct Iterate streams to close, then aggregatetheir ledger values in stream order and may also merge incoming `collection`inputs during runtime hydration. A missing ledger remains a legacy snapshotdiff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex ec99cbb6a1..99065b5100 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -6645,6 +6645,14 @@ class GraphExecutionState(BaseModel):next_node = self._get_next_node()if next_node is not None:return next_node++ if (+ isinstance(self._scheduler(), _GenericGraphSchedulerAdapter)+ and self._can_use_direct_iterate_collect_planner()+ ):+ self._prepare_direct_iterate_collect()+ return self._get_next_node()+prepared_id = self._materializer().prepare(base_graph)while prepared_id is not None:@@ -6654,6 +6662,184 @@ class GraphExecutionState(BaseModel):return next_node+ def _get_direct_iterate_collect_nodes(self) -> Optional[tuple[str, str, str, str]]:+ """Return the source, iterator, body, and collector for the narrow direct planner shape."""++ if self._legacy_snapshot_loaded or len(self.graph.nodes) != 4 or len(self.graph.edges) != 3:+ return None++ 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) != 1 or len(collector_ids) != 1:+ return None+ iterator_id = iterator_ids[0]+ collector_id = collector_ids[0]++ collection_edges = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)+ item_edges = self.graph._get_input_edges(collector_id, ITEM_FIELD)+ if len(collection_edges) != 1 or len(item_edges) != 1:+ return None+ collection_edge = collection_edges[0]+ item_edge = item_edges[0]+ if collection_edge.source.field != COLLECTION_FIELD or item_edge.destination.field != ITEM_FIELD:+ return None+ if collection_edge.destination.node_id != iterator_id:+ return None++ body_id = item_edge.source.node_id+ if body_id in {iterator_id, collector_id}:+ return None+ body = self.graph.get_node(body_id)+ if isinstance(body, (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] != Edge(+ source=EdgeConnection(node_id=iterator_id, field=ITEM_FIELD),+ destination=EdgeConnection(node_id=body_id, field=body_input_edges[0].destination.field),+ ):+ return None+ if body_input_edges[0].source.field != ITEM_FIELD:+ return None++ source_id = collection_edge.source.node_id+ if source_id in {iterator_id, body_id, collector_id}:+ return None+ source = self.graph.get_node(source_id)+ if isinstance(source, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)):+ return None+ if self.graph._get_input_edges(source_id):+ return None+ if self.graph._get_output_edges(source_id) != [collection_edge]:+ return None+ if self.graph._get_output_edges(iterator_id) != [body_input_edges[0]]:+ return None+ if self.graph._get_output_edges(body_id) != [item_edge]:+ return None+ if self.graph._get_input_edges(collector_id) != [item_edge]:+ return None++ return source_id, iterator_id, body_id, collector_id++ def _can_use_direct_iterate_collect_planner(self) -> bool:+ """Use fresh planner ownership only for the exact direct stream shape."""++ return self._get_direct_iterate_collect_nodes() is not None++ def _create_direct_execution_node_copy(+ self, source_node_id: str, iteration_index: int = -1, iteration_path: tuple[int, ...] = ()+ ) -> BaseInvocation:+ source_node = self.graph.get_node(source_node_id)+ new_node = source_node.model_copy(deep=True)+ new_node.id = uuid_string()+ if isinstance(new_node, IterateInvocation):+ new_node.index = iteration_index+ if iteration_index >= 0 or isinstance(new_node, CollectInvocation):+ new_node.use_cache = False+ self._tx_add_execution_node(new_node)+ self._add_execution_graph_node(new_node.id)+ self._register_prepared_exec_node(new_node.id, source_node_id)+ self._prepared_registry().set_iteration_path(new_node.id, iteration_path)+ return new_node++ def _attach_direct_execution_edges(self, exec_node_id: str, edges: Iterable[Edge]) -> list[Edge]:+ attached_edges = [+ Edge(+ source=edge.source,+ destination=EdgeConnection(node_id=exec_node_id, field=edge.destination.field),+ )+ for edge in edges+ ]+ self._tx_add_execution_edges(attached_edges)+ self._add_execution_graph_edges(attached_edges)+ return attached_edges++ def _initialize_direct_execution_node(self, exec_node_id: str, input_edges: Iterable[Edge]) -> None:+ input_edges = list(input_edges)+ self._tx_set_mapping(+ self.indegree,+ exec_node_id,+ sum(1 for edge in input_edges if edge.source.node_id not in self.executed),+ )+ scheduler = self._scheduler()+ assert isinstance(scheduler, _GenericGraphSchedulerAdapter)+ scheduler.register_node(exec_node_id)+ self._enqueue_if_ready(exec_node_id)++ def _mark_direct_source_empty(self, source_node_id: str) -> None:+ """Record an empty direct iterator source without entering the legacy materializer."""++ self._tx_set_mapping(self.source_prepared_mapping, source_node_id, set())+ self._mark_source_executed(source_node_id)+ if isinstance(self.graph.get_node(source_node_id), IterateInvocation):+ self._record_empty_iterate_stream(source_node_id)++ def _prepare_direct_iterate_collect(self) -> None:+ """Expand the fresh direct stream shape without invoking the legacy materializer."""++ node_ids = self._get_direct_iterate_collect_nodes()+ if node_ids is None:+ return+ source_id, iterator_id, body_id, collector_id = node_ids++ 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, ())+ return++ if collector_id in self.source_prepared_mapping:+ return++ if source_id not in self.executed:+ return+ source_exec_id = next(iter(self.source_prepared_mapping[source_id]))+ source_output = self.results[source_exec_id]+ collection_edge = self.graph._get_input_edges(iterator_id, COLLECTION_FIELD)[0]+ collection = getattr(source_output, collection_edge.source.field)+ if not isinstance(collection, list):+ raise ValueError("Direct Iterate collection source must produce a list")++ iterator_exec_ids: list[str] = []+ body_exec_ids: list[str] = []+ body_input_edge = self.graph._get_input_edges(body_id)[0]+ collect_item_edge = self.graph._get_input_edges(collector_id, ITEM_FIELD)[0]+ for index in range(len(collection)):+ iterator_node = self._create_direct_execution_node_copy(iterator_id, index, (index,))+ iterator_edges = [+ Edge(+ source=EdgeConnection(node_id=source_exec_id, field=collection_edge.source.field),+ destination=EdgeConnection(node_id="", field=collection_edge.destination.field),+ )+ ]+ attached_iterator_edges = self._attach_direct_execution_edges(iterator_node.id, iterator_edges)+ self._initialize_direct_execution_node(iterator_node.id, attached_iterator_edges)+ iterator_exec_ids.append(iterator_node.id)++ body_node = self._create_direct_execution_node_copy(body_id, iteration_path=(index,))+ body_edges = [+ Edge(+ source=EdgeConnection(node_id=iterator_node.id, field=body_input_edge.source.field),+ destination=EdgeConnection(node_id="", field=body_input_edge.destination.field),+ )+ ]+ attached_body_edges = self._attach_direct_execution_edges(body_node.id, body_edges)+ self._initialize_direct_execution_node(body_node.id, attached_body_edges)+ body_exec_ids.append(body_node.id)++ if not iterator_exec_ids:+ self._mark_direct_source_empty(iterator_id)+ self._mark_direct_source_empty(body_id)++ collector_node = self._create_direct_execution_node_copy(collector_id, iteration_path=())+ collector_edges = [+ Edge(+ source=EdgeConnection(node_id=body_exec_id, field=collect_item_edge.source.field),+ destination=EdgeConnection(node_id="", field=collect_item_edge.destination.field),+ )+ for body_exec_id in body_exec_ids+ ]+ 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 _reset_runtime_caches(self) -> None:self._ready_queues = {}self._ready_node_ids = set()diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex a2ff4f54ee..b4880d9d9e 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -8,6 +8,7 @@ from unittest.mock import Mock, patchimport pytestfrom pydantic import ValidationError+from invokeai.app.invocations.collections import CollectionConcatInvocationfrom invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.invocations.loops import (ForInvocation,@@ -246,6 +247,41 @@ def _nested_for_iterate_collect_graph(*, outer_collection: list[list[str]] | Nonreturn graph+def _direct_iterate_body_collect_graph(*, collection: list[Any] | None = None, with_after: bool = False) -> Graph:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="source", first=[] if collection is None else collection))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(AnyTypeTestInvocation(id="body"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="source", field="collection"),+ destination=EdgeConnection(node_id="iterate", field="collection"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="iterate", field="item"),+ destination=EdgeConnection(node_id="body", field="value"),+ )+ )+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="body", field="value"),+ destination=EdgeConnection(node_id="collect", field="item"),+ )+ )+ if with_after:+ graph.add_node(AnyTypeTestInvocation(id="after"))+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="collect", field="collection"),+ destination=EdgeConnection(node_id="after", field="value"),+ )+ )+ return graph++def _flat_for_state_graph(continue_condition: bool) -> Graph:graph = Graph()graph.add_node(ForInvocation(id="for", collection=[1, 2, 3], state=LoopState(values={"count": 0})))@@ -560,6 +596,15 @@ def _final_for_output(state: GraphExecutionState) -> Any:return state.results[final_for_id]+def _source_output(state: GraphExecutionState, source_id: str) -> Any:+ execution_id = next(+ execution_id+ for execution_id, prepared_source_id in state.prepared_source_mapping.items()+ if prepared_source_id == source_id and execution_id in state.results+ )+ return state.results[execution_id]++def _execution_edge_projection(state: GraphExecutionState) -> tuple[tuple[str, str, str, str, str], ...]:return tuple(sorted(@@ -1184,6 +1229,180 @@ def test_nested_for_iterate_collect_generic_rehydrates_after_inner_completion()assert _state_projection(resumed_state) == _state_projection(expected_state)+def test_direct_iterate_body_collect_fresh_execution_preserves_order_and_none() -> None:+ collection = ["first", None, "last"]+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection))++ with (+ patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("canonical Iterate -> body -> Collect must not use materializer.prepare"),+ ) as prepare,+ patch.object(+ graph_module._ExecutionMaterializer,+ "_get_collect_iteration_mapping_groups",+ side_effect=AssertionError("canonical Iterate -> body -> Collect must not group collector inputs"),+ ) as group_collector_inputs,+ ):+ trace, state = _run_graph(state)++ assert trace.count("iterate") == len(collection)+ assert trace.count("body") == len(collection)+ assert trace.count("collect") == 1+ assert _source_output(state, "collect").collection == collection+ assert state.is_complete()+ assert isinstance(state._execution_scheduler, _GenericGraphSchedulerAdapter)+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()+++def test_direct_iterate_body_collect_fresh_execution_handles_empty_input() -> None:+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=[]))+ with (+ patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("canonical empty Iterate -> body -> Collect must not use materializer.prepare"),+ ) as prepare,+ patch.object(+ graph_module._ExecutionMaterializer,+ "_get_collect_iteration_mapping_groups",+ side_effect=AssertionError("canonical empty Iterate -> body -> Collect must not group collector inputs"),+ ) as group_collector_inputs,+ ):+ trace, state = _run_graph(state)++ assert "iterate" not in trace+ assert "body" not in trace+ assert trace[-1] == "collect"+ assert _source_output(state, "collect").collection == []+ assert state.is_complete()+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()+++ "collection",+ [+ ["first", None, "last"],+ [],+ ],+ ids=["ordered-values-including-none", "empty"],+)+def test_direct_iterate_body_collect_matches_forced_compatibility_scheduler(collection: list[Any]) -> None:+ generic_trace, generic_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection))+ )+ compatibility_trace, compatibility_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace+ assert _source_output(generic_state, "collect").collection == collection+ assert _source_output(compatibility_state, "collect").collection == collection+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)+ assert _state_projection(generic_state) == _state_projection(compatibility_state)++[email protected]("force_compatibility_scheduler", [False, True])+def test_direct_iterate_body_collect_partial_dump_load_resume_matches_fresh_execution(+ force_compatibility_scheduler: bool,+) -> None:+ collection = ["first", None, "last"]+ expected_trace, expected_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ partial_trace, partial_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after=2,+ )++ restored = load_execution_state(dump_execution_state(partial_state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)+ resumed_trace, resumed_state = _run_graph(+ restored,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )++ assert partial_trace + resumed_trace == expected_trace+ assert _source_output(resumed_state, "collect").collection == collection+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ if force_compatibility_scheduler:+ assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)+++def test_direct_iterate_body_collect_empty_checkpoint_rehydrates_without_materializer() -> None:+ _partial_trace, partial_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=[])), stop_after=1+ )+ with (+ patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("empty canonical checkpoint must not use materializer.prepare"),+ ) as prepare,+ patch.object(+ graph_module._ExecutionMaterializer,+ "_get_collect_iteration_mapping_groups",+ side_effect=AssertionError("empty canonical checkpoint must not group collector inputs"),+ ) as group_collector_inputs,+ ):+ resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))++ assert resumed_trace == ["collect"]+ assert _source_output(resumed_state, "collect").collection == []+ assert resumed_state.is_complete()+ prepare.assert_not_called()+ group_collector_inputs.assert_not_called()+++def test_direct_iterate_body_collect_failure_rehydrates_pending_state_without_replanning() -> None:+ trace, failed_state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["first", "last"])),+ fail_source_id="body",+ )+ assert trace[0] == "source"+ assert trace.count("iterate") == 2+ assert trace[-1] == "body"+ assert failed_state.has_error()++ restored = load_execution_state(dump_execution_state(failed_state))+ assert restored.has_error()+ assert restored.source_prepared_mapping.get("collect")+ assert restored.is_complete()+++def test_direct_iterate_body_collect_with_downstream_consumer_uses_fallback_materializer() -> None:+ prepare_calls = 0+ original_prepare = graph_module._ExecutionMaterializer.prepare++ def prepare_spy(materializer: Any, base_graph: Any = None) -> Any:+ nonlocal prepare_calls+ prepare_calls += 1+ return original_prepare(materializer, base_graph)++ with patch.object(graph_module._ExecutionMaterializer, "prepare", autospec=True, side_effect=prepare_spy):+ trace, state = _run_graph(+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], with_after=True))+ )++ assert trace[-1] == "after"+ assert _source_output(state, "after").value == ["value"]+ assert state.is_complete()+ assert prepare_calls > 0++def test_direct_flat_for_completion_persists_continuations_and_final_tokens() -> None:trace, state = _run(GraphExecutionState(graph=_flat_for_graph()))