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): isolate generic For planning

JPPhoto304ef7d782de
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index f01e6f34b7..12739df293 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -82,6 +82,26 @@ body paths, and other mixed shapes remain on the compatibility scheduler.
Unsupported shapes, including independent iterator-derived body inputs, mixed nested `For`/`Iterate` bodies, escaping
body paths, ambiguous returns, and arbitrary cyclic graphs, are rejected before execution.
+## Generic `For` migration matrix
+
+`_GenericForPlanner` owns these fresh shapes. `_ExecutionMaterializer` remains the compatibility facade for every other
+shape and for explicitly forced compatibility runs:
+
+- One flat `For`/`ForReturn`: literal empty or non-empty collection, supported non-empty input producer, or the exact
+ four-node/four-edge empty input producer with no downstream consumer.
+- Canonical two-level nested `For` with a non-empty literal outer collection or supported non-empty input producer;
+ empty input-driven outer results remain compatibility-owned.
+- Exact two-sibling nested `For` fan-in through non-empty `CollectionConcat`.
+- Exact serial three-level nested `For`, including its statically non-empty `CollectionConcat` producer variant.
+- Exact serial four-level nested `For`.
+- Exact bounded outer `For`/`Iterate`/`Collect`.
+- Exact serial two-`Iterate` nested outer-`For` shape with one ordinary final consumer.
+
+Compatibility-owned shapes include legacy snapshots, unsupported input producers, extra nodes or consumers, fan-out,
+malformed linkage or output-scope edges, nested `For` depth five or greater, unsupported sibling or deeper shapes,
+unsupported mixed control flow, and saved-workflow or `If`-containing `For` graphs. No invocation emits or requires a
+literal successor node ID. This matrix changes no invocation, API, saved-workflow, frontend, or generated-schema contract.
+
## Persistence and validation
Prepared execution nodes, source/prepared mappings, iteration paths, results, indegrees, and finalized loop contexts
@@ -100,8 +120,9 @@ iteration-path, and workflow-call-depth identity, and stale or cross-scope effec
never encode `loop_linkage` as a data token. A fresh graph with exactly one static flat `For`/`ForReturn` pair,
including an empty literal collection, a supported non-empty input-driven collection producer, or the exact bounded
empty input-driven producer shape, now uses the generic scheduler adapter for readiness and continuation transitions.
-Graph state owns the generic continuation boundary: it carries returned state, honors `continue_condition`, materializes the next body
-iteration, and finalizes the aggregate. An empty literal collection completes through the existing synthetic terminal
+Graph state owns the generic continuation boundary. `_GenericForPlanner` owns admitted For-specific preparation,
+materializes the next body iteration, preserves frame paths and carried state, and finalizes nested completion. It
+shares only low-level execution-node construction mechanics with the compatibility materializer. An empty literal collection completes through the existing synthetic terminal
`For` result without running the body or `ForReturn`. The generic scheduler remains opaque and never receives a literal
successor node ID. The compatibility continuation bridge is retained only for unsupported loop shapes and explicitly
legacy-loaded snapshots. Empty input-driven shapes outside the exact four-node/four-edge bounded topology, unsupported
@@ -195,13 +216,11 @@ activation
ports and literal successor IDs remain absent, while unsupported loop shapes and saved-workflow control flow remain on
their compatibility paths until differential coverage proves their generic replacements.
-The engine still owns runtime node materialization and queue readiness for loop-containing graphs that require empty or
-unsupported input-driven `For`, deeper nested/mixed control flow, and existing snapshots. Ordinary static DAGs, legacy-shaped `If` graphs,
-direct `Iterate`/`Collect`-only graphs, and supported fresh static flat `For` graphs now use the generic opaque
-plan/scheduler through a compatibility projection. This is intentional:
-the generic records preserve tested loop semantics first, while the old execution graph remains the fallback for control
-lowerings, legacy snapshots, and unsupported mixed loop shapes. No activation or stream ports are added to author-time
-graph JSON.
+The engine keeps compatibility materialization and queue readiness for loop-containing graphs outside the migration
+matrix and for existing snapshots. Admitted fresh `For` graphs use the generic opaque plan/scheduler plus
+`_GenericForPlanner`; `_ExecutionNodeBuilder` supplies shared low-level graph mutation mechanics. Ordinary static DAGs,
+legacy-shaped `If` graphs, and direct `Iterate`/`Collect`-only graphs retain their existing generic or compatibility
+routes. No activation, stream, or continuation ports are added to author-time graph JSON.
Exact fresh serial nested-`Iterate` chains through eight levels use the generic planner for ordered frame expansion,
empty-stream closure, checkpoint rehydration, source completion, and failure parity. Nine-level or deeper chains,
five-level-or-deeper or unsupported sibling nested loops, and unsupported mixed shapes remain compatibility-owned. The exact fresh two-sibling `For`/`ForReturn` `CollectionConcat` fan-in shape, the exact fresh three-level serial nested-`For` shape with its bounded static `CollectionConcat` producer, and the exact fresh four-level serial nested-`For` shape are generic-routed. This migration does not modify any file under `invokeai/frontend/...`, including generated schemas; the existing
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 3ccba39508..481f5284b3 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -152,8 +152,10 @@ A fresh graph with exactly one flat `For`/`ForReturn` pair and ordinary body nod
literal collection, a supported non-empty input-driven collection, or the exact four-node/four-edge empty input-driven
shape with one inputless producer and no downstream node. 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 execution-node copies, input hydration, iteration paths, and body
-expansion. Other empty/input-driven shapes, five-level-or-deeper or sibling loops outside the exact two-sibling nested-`For` `CollectionConcat` fan-in shape, mixed control flow, and saved-workflow calls remain
+to the generic scheduler. The admitted For planner owns For-specific preparation, continuation, input hydration,
+iteration paths, and body expansion; it shares only low-level execution-node construction mechanics with the
+compatibility materializer. Other empty/input-driven shapes, five-level-or-deeper or sibling loops outside the exact
+two-sibling nested-`For` `CollectionConcat` fan-in shape, mixed control flow, and saved-workflow calls remain
on the compatibility scheduler until their own differential gates are complete. One narrow fresh two-level nested-`For` shape (one non-empty literal outer
collection, one inner `For` sourced from `outer.item`, and no continuation nodes) now uses the generic adapter;
deeper-than-four-level, multiple-child shapes outside the exact two-sibling `CollectionConcat` fan-in contract, other empty/input-driven, mixed, and legacy-loaded shapes remain compatibility-owned.
@@ -588,11 +590,15 @@ Workflow-call note:
- `_PreparedExecRegistry` Owns the relationship between source graph nodes and prepared execution graph nodes, plus
cached metadata such as iteration path and runtime state.
-- `_ExecutionMaterializer` Expands source graph nodes into concrete execution graph nodes when an unsupported or legacy
- shape runs out of ready work. On those compatibility paths it owns iterator expansion, collector grouping,
+- `_ExecutionMaterializer` is the compatibility planner facade. It expands source graph nodes into concrete execution
+ graph nodes when an unsupported or legacy shape runs out of ready work. On those compatibility paths it owns iterator expansion, collector grouping,
prepared-parent selection, and creation of execution-graph edges. When matching prepared parents for a downstream
exec node, skipped prepared exec nodes are ignored and cannot be selected as live inputs.
The class lives in `graph_materializer.py` and is re-exported by `graph.py`.
+- `_GenericForPlanner` owns admitted fresh `For`/`ForReturn` preparation, continuation transitions, carried state,
+ frame paths, and nested `For` completion. It uses `_ExecutionNodeBuilder` only for low-level copy, edge, input,
+ and scheduler-registration mechanics; it does not construct `_ExecutionMaterializer`. Unsupported and legacy shapes
+ retain the compatibility facade.
- Private `graph_iterate_planner.py` expands the supported direct and body-mediated Iterate/Collect shapes.
Graph-state method wrappers preserve the admission, copy creation, edge attachment, and atomic preparation entry
points. The planner continues to use the graph state's journal, mappings, caches, and scheduler.
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index b3b172159d..34af012938 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -83,6 +83,7 @@ from invokeai.app.services.shared.graph_execution_runtime import (
_DirectIterateCollectFanIn,
_ExecutionRuntime,
)
+from invokeai.app.services.shared.graph_for_planner import _GenericForPlanner
from invokeai.app.services.shared.graph_if_activation import _IfActivationController
from invokeai.app.services.shared.graph_iterate_planner import (
_attach_direct_execution_edges,
@@ -320,6 +321,7 @@ class GraphExecutionState(BaseModel):
_prepared_exec_registry: Optional[_PreparedExecRegistry] = PrivateAttr(default=None)
_if_activation_controller_instance: Optional[_IfActivationController] = PrivateAttr(default=None)
_execution_materializer: Optional[_ExecutionMaterializer] = PrivateAttr(default=None)
+ _generic_for_planner: Optional[_GenericForPlanner] = PrivateAttr(default=None)
_execution_scheduler: Optional[_ExecutionScheduler | _GenericGraphSchedulerAdapter] = PrivateAttr(default=None)
_execution_runtime: Optional[_ExecutionRuntime] = PrivateAttr(default=None)
_for_parent_iteration_paths_cache: dict[str, set[tuple[int, ...]]] = PrivateAttr(default_factory=dict)
@@ -432,6 +434,7 @@ class GraphExecutionState(BaseModel):
def _reset_apply_derived_caches(self) -> None:
self._prepared_exec_registry = None
self._execution_materializer = None
+ self._generic_for_planner = None
self._execution_scheduler = None
self._generic_graph_scheduler = None
self._if_activation_controller_instance = None
@@ -612,6 +615,22 @@ class GraphExecutionState(BaseModel):
self._execution_materializer = _ExecutionMaterializer(self)
return self._execution_materializer
+ def _for_planner(self) -> _GenericForPlanner:
+ if self._generic_for_planner is None:
+ self._generic_for_planner = _GenericForPlanner(self)
+ return self._generic_for_planner
+
+ def _create_for_body_iteration(self, source_for_id: str, prepared_for_id: str) -> Optional[str]:
+ if self._is_generic_graph_scheduler(self._scheduler()) and self._can_use_generic_for_scheduler():
+ return self._for_planner().create_for_body_iteration(
+ source_for_id=source_for_id,
+ prepared_for_id=prepared_for_id,
+ )
+ return self._materializer().create_for_body_iteration(
+ source_for_id=source_for_id,
+ prepared_for_id=prepared_for_id,
+ )
+
def _get_for_parent(self, exec_node_id: str) -> Optional[str]:
source_return_id = self._prepared_registry().get_source_node_id(exec_node_id)
iteration_path = self._get_iteration_path(exec_node_id)
@@ -703,9 +722,12 @@ class GraphExecutionState(BaseModel):
else:
self._tx_set_attr(existing, "value", copydeep(token.value))
- def _apply_generic_for_continuation(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:
- """Apply the graph-state continuation boundary for a supported fresh For run."""
-
+ def _apply_for_continuation(
+ self,
+ exec_node_id: str,
+ output: BaseInvocationOutput,
+ planner: _GenericForPlanner | _ExecutionMaterializer,
+ ) -> Optional[str]:
if not isinstance(output, ForReturnInvocationOutput):
return None
if not isinstance(self.execution_graph.get_node(exec_node_id), ForReturnInvocation):
@@ -733,7 +755,7 @@ class GraphExecutionState(BaseModel):
next_index = for_node.index + 1
if next_index >= len(for_node.collection) or for_return_node.continue_condition is False:
self._finalize_for_outputs(for_exec_node_id, source_for_id, source_return_id, output)
- self._materializer().create_nested_for_return(
+ planner.create_nested_for_return(
inner_for_id=source_for_id,
prepared_inner_for_id=for_exec_node_id,
)
@@ -745,7 +767,7 @@ class GraphExecutionState(BaseModel):
collection = for_node.collection
self._tx_set_attr(for_node, "collection", [])
- next_for_id = self._materializer().create_for_iteration(
+ next_for_id = planner.create_for_iteration(
source_for_id=source_for_id,
iteration_index=next_index,
collection=collection,
@@ -756,13 +778,18 @@ class GraphExecutionState(BaseModel):
if self._is_generic_graph_scheduler(self._scheduler()) and can_use_nested_iterate_planner(self):
prepare_nested_iterate_bodies(self)
else:
- self._materializer().create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=next_for_id)
+ planner.create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=next_for_id)
return None
+ def _apply_generic_for_continuation(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:
+ """Apply graph-state continuation boundary for an admitted fresh For run."""
+
+ return self._apply_for_continuation(exec_node_id, output, self._for_planner())
+
def _try_schedule_next_for_iteration(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:
"""Advance a compatibility-owned loop continuation."""
- return self._apply_generic_for_continuation(exec_node_id, output)
+ return self._apply_for_continuation(exec_node_id, output, self._materializer())
def _can_use_generic_two_sibling_nested_for_scheduler(
self, for_nodes: list[ForInvocation], return_nodes: list[ForReturnInvocation], source_graph: Any
@@ -2751,10 +2778,15 @@ class GraphExecutionState(BaseModel):
prepare_eight_level_nested_iterate_sequences(self)
return self._get_next_node()
- prepared_id = self._materializer().prepare(base_graph)
+ planner = (
+ self._for_planner()
+ if isinstance(self._scheduler(), _GenericGraphSchedulerAdapter) and self._can_use_generic_for_scheduler()
+ else self._materializer()
+ )
+ prepared_id = planner.prepare(base_graph)
while prepared_id is not None:
- prepared_id = self._materializer().prepare(base_graph)
+ prepared_id = planner.prepare(base_graph)
if next_node is None:
next_node = self._get_next_node()
@@ -2814,6 +2846,7 @@ class GraphExecutionState(BaseModel):
self._prepared_exec_metadata = {}
self._prepared_exec_registry = None
self._execution_materializer = None
+ self._generic_for_planner = None
self._execution_scheduler = None
self._generic_graph_scheduler = None
self._execution_runtime = None
@@ -3375,6 +3408,8 @@ class GraphExecutionState(BaseModel):
return self._materializer().create_execution_node(node_id, iteration_node_map, enforce_admission=False)
def _iterator_graph(self, base: Optional["nx.DiGraph"] = None) -> "nx.DiGraph":
+ if isinstance(self._scheduler(), _GenericGraphSchedulerAdapter) and self._can_use_generic_for_scheduler():
+ return self._for_planner().iterator_graph(base)
return self._materializer().iterator_graph(base)
def _get_node_iterators(self, node_id: str, it_graph: Optional["nx.DiGraph"] = None) -> list[str]:
diff --git a/invokeai/app/services/shared/graph_for_planner.py b/invokeai/app/services/shared/graph_for_planner.py
new file mode 100644
index 0000000000..ed6f0a9ad5
--- /dev/null
+++ b/invokeai/app/services/shared/graph_for_planner.py
@@ -0,0 +1,60 @@
+"""Generic-owned For expansion seam.
+
+The generic scheduler owns continuation admission and transition selection. This
+planner owns admitted For expansion while sharing low-level execution-node
+construction mechanics with the compatibility planner.
+"""
+
+from typing import TYPE_CHECKING, Any, Optional
+
+import networkx as nx
+
+from invokeai.app.invocations.loops import LoopState
+from invokeai.app.services.shared.graph_materializer import _ExecutionNodeBuilder
+
+if TYPE_CHECKING:
+ from invokeai.app.services.shared.graph import GraphExecutionState
+
+
+class _GenericForPlanner:
+ """Prepare admitted For contexts without calling compatibility entry points."""
+
+ def __init__(self, state: "GraphExecutionState") -> None:
+ self._state = state
+ self._builder = _ExecutionNodeBuilder(state)
+
+ def prepare(self, base_graph: Any) -> Optional[str]:
+ """Prepare one admitted source node without constructing compatibility facade."""
+
+ return self._builder.prepare(base_graph)
+
+ def iterator_graph(self, base: Optional[nx.DiGraph] = None) -> nx.DiGraph:
+ return self._builder.iterator_graph(base)
+
+ def create_for_iteration(
+ self,
+ source_for_id: str,
+ iteration_index: int,
+ collection: list[Any],
+ state: LoopState,
+ iteration_path: tuple[int, ...],
+ ) -> str:
+ return self._builder._create_for_iteration_generic(
+ source_for_id=source_for_id,
+ iteration_index=iteration_index,
+ collection=collection,
+ state=state,
+ iteration_path=iteration_path,
+ )
+
+ def create_for_body_iteration(self, source_for_id: str, prepared_for_id: str) -> Optional[str]:
+ return self._builder._create_for_body_iteration_generic(
+ source_for_id=source_for_id,
+ prepared_for_id=prepared_for_id,
+ )
+
+ def create_nested_for_return(self, inner_for_id: str, prepared_inner_for_id: str) -> Optional[str]:
+ return self._builder._create_nested_for_return_generic(
+ inner_for_id=inner_for_id,
+ prepared_inner_for_id=prepared_inner_for_id,
+ )
diff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.py
index 38639b5212..99bf64626b 100644
--- a/invokeai/app/services/shared/graph_materializer.py
+++ b/invokeai/app/services/shared/graph_materializer.py
@@ -31,12 +31,12 @@ if TYPE_CHECKING:
from invokeai.app.services.shared.graph import GraphExecutionState
-class _ExecutionMaterializer:
- """Expands source-graph nodes into concrete execution-graph nodes for the current runtime state.
+class _ExecutionNodeBuilder:
+ """Builds concrete execution-graph nodes for a selected runtime planner.
- `GraphExecutionState.next()` calls into this helper when no prepared exec node is ready. The materializer chooses
- the next source node that can be expanded, creates the corresponding exec nodes in the execution graph, wires their
- inputs, and initializes their scheduler state.
+ This class contains low-level copy, edge, input, and iteration mechanics. A
+ planner owns whether those mechanics are used for generic or compatibility
+ execution.
"""
def __init__(self, state: "GraphExecutionState") -> None:
@@ -475,6 +475,12 @@ class _ExecutionMaterializer:
self._initialize_execution_node(prepared_return_node.id, attached_return_edges)
return prepared_return_node.id
+ # Generic For planning uses private aliases. Compatibility callers retain
+ # the public methods as an explicit fallback seam.
+ _create_for_iteration_generic = create_for_iteration
+ _create_for_body_iteration_generic = create_for_body_iteration
+ _create_nested_for_return_generic = create_nested_for_return
+
def _create_serial_nested_iterate_copy(
self,
source_node_id: str,
@@ -811,10 +817,10 @@ class _ExecutionMaterializer:
):
self._mark_empty_for_complete(source_inner_for_id)
for inner_prepared_id in inner_prepared_ids:
- self.create_nested_for_return(source_inner_for_id, inner_prepared_id)
+ self._create_nested_for_return_generic(source_inner_for_id, inner_prepared_id)
else:
for inner_prepared_id in inner_prepared_ids:
- self.create_for_body_iteration(
+ self._create_for_body_iteration_generic(
source_for_id=source_inner_for_id,
prepared_for_id=inner_prepared_id,
)
@@ -1711,3 +1717,9 @@ class _ExecutionMaterializer:
self._mark_empty_for_complete(next_node_id)
return new_node_ids[0]
+
+
+class _ExecutionMaterializer(_ExecutionNodeBuilder):
+ """Compatibility planner facade for unsupported and legacy graphs."""
+
+ pass
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index e08d0efeb3..658b822aa4 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -150,7 +150,7 @@ class _ExecutionScheduler:
prepared_for_node.index,
)
if prepared_exec_path[: len(prepared_for_path)] == prepared_for_path:
- self._state._materializer().create_for_body_iteration(
+ self._state._create_for_body_iteration(
source_for_id=source_for_id, prepared_for_id=prepared_for_id
)
return
@@ -189,7 +189,7 @@ class _ExecutionScheduler:
)
for child_id in deferred_node_ids
):
- self._state._materializer().create_for_body_iteration(
+ self._state._create_for_body_iteration(
source_for_id=source_for_id, prepared_for_id=prepared_for_id
)
return
@@ -201,9 +201,7 @@ class _ExecutionScheduler:
for prepared_iterate_id in self._state._prepared_registry().get_prepared_ids(deferred_node_ids[0])
):
continue
- self._state._materializer().create_for_body_iteration(
- source_for_id=source_for_id, prepared_for_id=prepared_for_id
- )
+ self._state._create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=prepared_for_id)
return
def _decrement_child_indegree(self, child_exec_node_id: str, parent_exec_node_id: str) -> None:
@@ -331,9 +329,7 @@ class _ExecutionScheduler:
nested_body.iterate_node_id
)
):
- self._state._materializer().create_for_body_iteration(
- source_for_id=source_for_id, prepared_for_id=exec_node_id
- )
+ self._state._create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=exec_node_id)
elif nested_body is None:
self._try_materialize_deferred_nested_for_body(exec_node_id)
else:
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index f733e5d261..7c5707be71 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import json
from itertools import product
from pathlib import Path
-from typing import Any
+from typing import Any, Callable
from unittest.mock import Mock, patch
import pytest
@@ -2098,6 +2098,70 @@ def test_flat_for_generic_path_does_not_use_compatibility_continuation_bridge(
assert _final_for_output(state).output_collection == [11, 12]
+def test_flat_for_generic_path_does_not_use_compatibility_materializer_helpers(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_compatibility_helper(*_: object, **__: object) -> None:
+ raise AssertionError("generic For execution used a compatibility materializer helper")
+
+ def fail_compatibility_materializer(*_: object, **__: object) -> None:
+ raise AssertionError("generic For instantiated compatibility materializer")
+
+ materializer_type = graph_module._ExecutionMaterializer
+ monkeypatch.setattr(graph_module, "_ExecutionMaterializer", fail_compatibility_materializer)
+ for method_name in ("create_for_iteration", "create_for_body_iteration", "create_nested_for_return"):
+ monkeypatch.setattr(materializer_type, method_name, fail_compatibility_helper)
+
+ trace, state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()))
+
+ assert trace == ["for", "body", "return", "for", "body", "return"]
+ assert state.is_complete()
+ assert _final_for_output(state).output_collection == [11, 12]
+
+
+ "graph_factory",
+ [
+ pytest.param(_flat_for_graph, id="flat"),
+ pytest.param(_input_driven_nested_for_graph, id="input-driven-nested"),
+ pytest.param(_two_sibling_nested_for_fan_in_graph, id="two-sibling"),
+ pytest.param(_three_level_nested_for_graph, id="three-level"),
+ pytest.param(_input_driven_three_level_nested_for_graph, id="input-driven-three-level"),
+ pytest.param(_four_level_nested_for_graph, id="four-level"),
+ pytest.param(_nested_for_iterate_collect_graph, id="nested-iterate-collect"),
+ pytest.param(_serial_two_level_nested_for_iterate_collect_graph, id="serial-nested-iterate"),
+ ],
+)
+def test_admitted_generic_for_shapes_do_not_construct_compatibility_materializer(
+ monkeypatch: pytest.MonkeyPatch,
+ graph_factory: Callable[[], Graph],
+) -> None:
+ def fail_compatibility_materializer(*_: object, **__: object) -> None:
+ raise AssertionError("generic For instantiated compatibility materializer")
+
+ monkeypatch.setattr(graph_module, "_ExecutionMaterializer", fail_compatibility_materializer)
+
+ trace, state = _run_graph_with_effects(GraphExecutionState(graph=graph_factory()))
+
+ assert trace
+ assert state.is_complete()
+
+
+def test_compatibility_for_path_does_not_construct_generic_planner(monkeypatch: pytest.MonkeyPatch) -> None:
+ def fail_generic_planner(*_: object, **__: object) -> None:
+ raise AssertionError("compatibility For instantiated generic planner")
+
+ monkeypatch.setattr(GraphExecutionState, "_for_planner", fail_generic_planner)
+
+ trace, state = _run_graph_with_effects(
+ GraphExecutionState(graph=_flat_for_graph()),
+ force_compatibility_scheduler=True,
+ )
+
+ assert trace == ["for", "body", "return", "for", "body", "return"]
+ assert state.is_complete()
+
+
def test_nested_for_generic_and_compatibility_paths_have_matching_completion() -> None:
def run(force_compatibility: bool) -> tuple[list[str], GraphExecutionState]:
state = GraphExecutionState(graph=_nested_for_graph())