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): declare For continuation effects

JPPhoto30bfdb148245
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 747b9b8235..088938ec1e 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -85,7 +85,14 @@ collections or state.
The execution-engine seam is additive to this loop contract. The session runner applies each result through
`GraphExecutionState.apply()` using a stable execution reference and records frame-aware output tokens and accepted
effects. Legacy `For`/`ForReturn` continuation scheduling is mirrored by a typed, frame-scoped
-`ContinuationRecord`. `Iterate` records ordered item tokens in a closed `StreamBuffer`; an empty `Iterate` records an
+`ContinuationRecord`. `ForInvocation` and `ForReturnInvocation` also declare one validated, frame-scoped
+`continuation` effect per prepared invocation. The `For` effect starts the `for` continuation with the current
+iteration and state; the `ForReturn` effect completes it with output, state, and the continue decision. These effects
+are persisted under the invocation reference. Session-built effect references carry graph-state, durable-frame,
+iteration-path, and workflow-call-depth identity, and stale or cross-scope effects are rejected before mutation. They
+never encode `loop_linkage` as a data token. The legacy scheduler still
+resolves the linkage, materializes the next iteration, aggregates output, finalizes the loop, and owns empty/nested/
+mixed loop behavior; this additive effect seam does not claim generic `For` scheduling. `Iterate` records ordered item tokens in a closed `StreamBuffer`; an empty `Iterate` records an
explicit 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.
diff --git a/invokeai/app/invocations/loops.py b/invokeai/app/invocations/loops.py
index 73e17f4102..18c67a85fb 100644
--- a/invokeai/app/invocations/loops.py
+++ b/invokeai/app/invocations/loops.py
@@ -141,6 +141,8 @@ class ForInvocationOutput(BaseInvocationOutput):
@invocation("for", version="1.3.1")
class ForInvocation(BaseInvocation):
+ execution_effects_enabled = True
+
collection: list[Any] = InputField(
description="The list of items to iterate over",
default=[],
@@ -162,7 +164,7 @@ class ForInvocation(BaseInvocation):
raise NotImplementedError("For loop nodes must be executed as part of a workflow graph")
state = self.state or LoopState()
- return ForInvocationOutput(
+ output = ForInvocationOutput(
loop_linkage=LOOP_LINKAGE_FIELD,
item=self.collection[self.index],
index=self.index,
@@ -171,6 +173,17 @@ class ForInvocation(BaseInvocation):
output_collection=[],
final_state=state,
)
+ execution = getattr(context, "execution", None)
+ if execution is not None and hasattr(execution, "start_continuation"):
+ execution.start_continuation(
+ "for",
+ payload={
+ "index": self.index,
+ "total": len(self.collection),
+ "state": state.model_dump(mode="json"),
+ },
+ )
+ return output
@invocation_output("for_return_output")
@@ -192,6 +205,8 @@ class ForReturnInvocationOutput(BaseInvocationOutput):
@invocation("for_return", version="1.3.2")
class ForReturnInvocation(BaseInvocation):
+ execution_effects_enabled = True
+
loop_linkage: Optional[Any] = InputField(
default=None,
description="The loop linkage from the matching For",
@@ -213,4 +228,15 @@ class ForReturnInvocation(BaseInvocation):
)
def invoke(self, context: InvocationContext) -> ForReturnInvocationOutput:
- return ForReturnInvocationOutput(output=self.output, state=self.state)
+ output = ForReturnInvocationOutput(output=self.output, state=self.state)
+ execution = getattr(context, "execution", None)
+ if execution is not None and hasattr(execution, "complete_continuation"):
+ execution.complete_continuation(
+ "for",
+ payload={
+ "output": self.output,
+ "state": self.state.model_dump(mode="json") if self.state is not None else None,
+ "continue_condition": self.continue_condition,
+ },
+ )
+ return output
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index 6ffdcbe5aa..ec5b9d0318 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -263,6 +263,9 @@ class DefaultSessionRunner(SessionRunnerBase):
source_invocation_id=queue_item.session.prepared_source_mapping[invocation.id],
queue_item=queue_item,
execution_frame=execution_ref.frame.iteration_path,
+ execution_state_id=execution_ref.state_id,
+ execution_frame_id=execution_ref.frame.frame_id,
+ execution_workflow_call_depth=execution_ref.frame.workflow_call_depth,
)
context = build_invocation_context(
data=data,
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 672b332d42..27d982dbc3 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -257,7 +257,19 @@ Current implementation is narrower: `IfInvocation` and non-empty
Direct `Iterate`/`Collect`-only graphs use the generic scheduler adapter for
readiness and completion, while the materializer still expands copies and
groups paths. `For`, `ForReturn`, workflow-call invocations, and mixed
-control-flow graphs remain on compatibility paths. For
+control-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
+iteration/state payload, and `ForReturn` completes it with output/state/
+continue-decision data. Session-built recorders bind the effect reference to
+the graph-state ID, durable frame ID, iteration path, and workflow-call depth;
+graph-state validation rejects a stale or cross-frame continuation before
+mutation. Graph state persists these effects under the invocation reference
+and excludes `loop_linkage` from token data. This is the
+invocation/effect ownership seam only: the legacy scheduler still resolves
+linkage, creates the next prepared iteration, aggregates outputs, finalizes
+the loop, and owns empty/nested/mixed materialization. Generic `For`
+scheduling is not claimed yet. For
`If`, generic readiness consumes opaque frame-local plan dependencies and requires
both matching private `ActivationGate` runtime state and a persisted activation token;
generic resolution retires unselected prepared nodes through scheduler discard. The forced compatibility
diff --git a/invokeai/app/services/shared/execution_effects.py b/invokeai/app/services/shared/execution_effects.py
index bd033b875b..583e1c06de 100644
--- a/invokeai/app/services/shared/execution_effects.py
+++ b/invokeai/app/services/shared/execution_effects.py
@@ -134,7 +134,10 @@ class ExecutionRef(_ExecutionModel):
token: ExecutionToken | None = None
template_node_id: str | None = Field(default=None, min_length=1)
execution_node_id: str | None = Field(default=None, min_length=1)
+ state_id: str | None = Field(default=None, min_length=1)
frame_path: tuple[int | str, ...] = ()
+ frame_id: str | None = Field(default=None, min_length=1)
+ workflow_call_depth: int | None = Field(default=None, ge=0)
scope: Literal["iteration", "final"] = "final"
@model_validator(mode="before")
@@ -334,6 +337,17 @@ class FailEffect(ExecutionEffect):
message: str = Field(min_length=1)
+class ContinuationEffect(ExecutionEffect):
+ """A frame-scoped semantic transition for a generic control-flow continuation."""
+
+ kind: Literal["continuation"] = "continuation"
+ operation: Literal["start", "complete"]
+ continuation_kind: str = Field(min_length=1)
+ payload: Any | None = None
+
+ _validate_payload = field_validator("payload")(_validate_json_serializable)
+
+
ExecutionEffectModel = Union[
SetValueEffect,
AddEdgeEffect,
@@ -343,6 +357,7 @@ ExecutionEffectModel = Union[
SpawnExecutionEffect,
AwaitEffect,
FailEffect,
+ ContinuationEffect,
]
# Descriptive aliases keep call sites free to use execution-specific names.
@@ -350,6 +365,7 @@ SetExecutionValueEffect = SetValueEffect
AddExecutionEdgeEffect = AddEdgeEffect
RemoveExecutionEdgeEffect = RemoveEdgeEffect
EmitExecutionEffect = EmitEffect
+ContinuationExecutionEffect = ContinuationEffect
class UnsupportedExecutionEffectError(RuntimeError):
@@ -444,6 +460,26 @@ class ExecutionInterface:
self._require_lifecycle_capability("fail")
self._recorder.record(FailEffect(execution_ref=self._recorder.execution_ref, message=message))
+ def start_continuation(self, continuation_kind: str, *, payload: Any | None = None) -> None:
+ self._recorder.record(
+ ContinuationEffect(
+ execution_ref=self._recorder.execution_ref,
+ operation="start",
+ continuation_kind=continuation_kind,
+ payload=payload,
+ )
+ )
+
+ def complete_continuation(self, continuation_kind: str, *, payload: Any | None = None) -> None:
+ self._recorder.record(
+ ContinuationEffect(
+ execution_ref=self._recorder.execution_ref,
+ operation="complete",
+ continuation_kind=continuation_kind,
+ payload=payload,
+ )
+ )
+
def _require_lifecycle_capability(self, effect_kind: str) -> ChildExecutionCapability:
if not self._recorder.allow_lifecycle_effects:
raise UnsupportedExecutionEffectError(f"Execution effect kind '{effect_kind}' is not supported")
@@ -524,22 +560,34 @@ class ExecutionEffectBatch:
class ExecutionEffectsRecorder:
"""Collects effects for one invocation run."""
- _SUPPORTED_EFFECT_KINDS = frozenset({"emit", "close_stream"})
+ _SUPPORTED_EFFECT_KINDS = frozenset({"emit", "close_stream", "continuation"})
def __init__(
self,
source_node_id: str = "context",
frame_path: tuple[int | str, ...] = (),
*,
+ state_id: str | None = None,
+ frame_id: str | None = None,
+ workflow_call_depth: int | None = None,
allow_lifecycle_effects: bool = False,
child_capability: ChildExecutionCapability | None = None,
) -> None:
self._effects: list[ExecutionEffect] = []
self.source_node_id = source_node_id
self.frame_path = frame_path
+ self.state_id = state_id
+ self.frame_id = frame_id
+ self.workflow_call_depth = workflow_call_depth
self.allow_lifecycle_effects = allow_lifecycle_effects
self.child_capability = child_capability
- self.execution_ref = ExecutionRef(execution_node_id=source_node_id, frame_path=frame_path)
+ self.execution_ref = ExecutionRef(
+ execution_node_id=source_node_id,
+ state_id=state_id,
+ frame_path=frame_path,
+ frame_id=frame_id,
+ workflow_call_depth=workflow_call_depth,
+ )
def record(self, effect: ExecutionEffect) -> None:
if not isinstance(effect, ExecutionEffect):
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 6ff37b246f..e670db930b 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -5134,7 +5134,7 @@ class GraphExecutionState(BaseModel):
return execution_ref.model_copy(deep=True)
if isinstance(execution_ref, BaseModel):
- values = execution_ref.model_dump(mode="python", warnings=False)
+ values = execution_ref.model_dump(mode="python", warnings=False, exclude_none=True)
elif isinstance(execution_ref, dict):
values = dict(execution_ref)
else:
@@ -5386,6 +5386,52 @@ class GraphExecutionState(BaseModel):
raise ValueError("Emit effect requires a data output token")
if self._value_from_object(token, "token_kind") == "stream_end":
raise ValueError("Emit effect cannot use a stream_end token")
+ elif effect_kind == "continuation":
+ continuation_kind = self._value_from_object(effect, "continuation_kind")
+ operation = self._value_from_object(effect, "operation")
+ expected_operation = "start" if isinstance(node, ForInvocation) else "complete"
+ if not isinstance(node, (ForInvocation, ForReturnInvocation)):
+ raise ValueError("Continuation effects are only supported by For control-flow nodes")
+ if continuation_kind != "for":
+ raise ValueError("Unsupported continuation effect kind")
+ if operation != expected_operation:
+ raise ValueError(
+ f"{type(node).__name__} continuation effect must use operation '{expected_operation}'"
+ )
+ continuation_owner = self._value_from_object(
+ effect,
+ "execution_ref",
+ "execution_reference",
+ "owner_ref",
+ "owner",
+ )
+ continuation_state_id = self._value_from_object(continuation_owner, "state_id", "session_id")
+ continuation_frame_path = self._value_from_object(
+ continuation_owner, "frame", "frame_path", "iteration_path"
+ )
+ if continuation_state_id not in (None, "", execution_ref.state_id):
+ raise ValueError("Continuation effect belongs to another graph execution state")
+ continuation_frame_id = self._value_from_object(continuation_owner, "frame_id")
+ if continuation_frame_id not in (None, "", execution_ref.frame.frame_id):
+ raise ValueError("Continuation effect belongs to another execution frame")
+ continuation_depth = self._value_from_object(
+ continuation_owner, "workflow_call_depth", "call_depth", "depth"
+ )
+ if continuation_depth not in (None, execution_ref.frame.workflow_call_depth):
+ raise ValueError("Continuation effect belongs to another workflow-call depth")
+ if continuation_state_id in (None, ""):
+ raise ValueError("Continuation effect is missing graph execution-state identity")
+ if continuation_frame_id in (None, ""):
+ raise ValueError("Continuation effect is missing durable frame identity")
+ if continuation_depth is None:
+ raise ValueError("Continuation effect is missing workflow-call depth")
+ if continuation_frame_path is None:
+ raise ValueError("Continuation effect is missing iteration-frame identity")
+ self._validate_execution_frame(
+ continuation_frame_path,
+ execution_ref,
+ "Continuation effect",
+ )
owner = self._value_from_object(
effect,
@@ -5404,7 +5450,7 @@ class GraphExecutionState(BaseModel):
if owner is None or not self._same_execution_owner(owner, execution_ref):
raise ValueError("Execution effect is not owned by execution reference")
if effect_kind is not None and (
- not isinstance(effect_kind, str) or effect_kind not in {"emit", "close_stream"}
+ not isinstance(effect_kind, str) or effect_kind not in {"emit", "close_stream", "continuation"}
):
raise ValueError(f"Unsupported execution effect kind: {effect_kind}")
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index ccb2719e6a..4c10460482 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -68,6 +68,12 @@ class InvocationContextData:
"""The ID of the invocation from which the currently executing invocation was prepared."""
execution_frame: tuple[int, ...] = ()
"""The active prepared execution node's loop iteration path."""
+ execution_state_id: str | None = None
+ """The owning graph execution-state identity for effect ownership validation."""
+ execution_frame_id: str | None = None
+ """The durable frame identity for effect ownership validation."""
+ execution_workflow_call_depth: int = 0
+ """The active workflow-call depth for effect ownership validation."""
class InvocationContextInterface:
@@ -987,6 +993,9 @@ class InvocationContext:
self.execution_effects = execution_effects or ExecutionEffectsRecorder(
source_node_id=source_node_id,
frame_path=data.execution_frame,
+ state_id=data.execution_state_id,
+ frame_id=data.execution_frame_id,
+ workflow_call_depth=data.execution_workflow_call_depth,
)
"""Effects recorded during the current invocation run."""
self.effects = self.execution_effects
@@ -1027,6 +1036,9 @@ def build_invocation_context(
execution_effects = ExecutionEffectsRecorder(
source_node_id=getattr(data.invocation, "id", None) or data.source_invocation_id or "context",
frame_path=data.execution_frame,
+ state_id=data.execution_state_id,
+ frame_id=data.execution_frame_id,
+ workflow_call_depth=data.execution_workflow_call_depth,
)
ctx = InvocationContext(
diff --git a/tests/app/services/session_processor/test_for_loop_processor_sqlite.py b/tests/app/services/session_processor/test_for_loop_processor_sqlite.py
index a0d9c9385b..ca1b868a77 100644
--- a/tests/app/services/session_processor/test_for_loop_processor_sqlite.py
+++ b/tests/app/services/session_processor/test_for_loop_processor_sqlite.py
@@ -185,6 +185,9 @@ def _build_test_invocation_context(data, services, is_canceled):
recorder = ExecutionEffectsRecorder(
source_node_id=data.invocation.id,
frame_path=data.execution_frame,
+ state_id=getattr(data, "execution_state_id", None),
+ frame_id=getattr(data, "execution_frame_id", None),
+ workflow_call_depth=getattr(data, "execution_workflow_call_depth", None),
)
return SimpleNamespace(
execution_effects=recorder,
diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.py
index 6a4a3de947..c222b7b197 100644
--- a/tests/app/services/shared/test_execution_effects.py
+++ b/tests/app/services/shared/test_execution_effects.py
@@ -12,11 +12,13 @@ from invokeai.app.invocations.baseinvocation import (
)
from invokeai.app.invocations.fields import InputField, OutputField
from invokeai.app.invocations.logic import IfInvocation, IfInvocationOutput
+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation, LoopState
from invokeai.app.services.shared.execution_effects import (
AddEdgeEffect,
AwaitEffect,
ChildExecutionHandle,
CloseStreamEffect,
+ ContinuationEffect,
EmitEffect,
ExecutionEffectsRecorder,
ExecutionInterface,
@@ -104,12 +106,18 @@ def test_context_default_recorder_preserves_execution_frame() -> None:
invocation=ExecutionEffectsTestInvocation(id="node"),
source_invocation_id="source",
execution_frame=(2, 1),
+ execution_state_id="state",
+ execution_frame_id="frame",
+ execution_workflow_call_depth=2,
),
is_canceled=lambda: False,
)
assert context.execution_effects.source_node_id == "node"
assert context.execution_effects.frame_path == (2, 1)
+ assert context.execution_effects.execution_ref.state_id == "state"
+ assert context.execution_effects.execution_ref.frame_id == "frame"
+ assert context.execution_effects.execution_ref.workflow_call_depth == 2
@pytest.mark.parametrize(
@@ -165,6 +173,174 @@ def test_iterate_invocation_declares_ordered_item_stream_effects(index: int, exp
assert close.token.token_kind == "stream_end"
+def test_for_invocation_declares_frame_scoped_continuation_start_effect() -> None:
+ context = _context()
+ context.execution_effects = ExecutionEffectsRecorder(source_node_id="for", frame_path=(4, 2))
+ context.execution = ExecutionInterface(context.execution_effects)
+ state = LoopState(values={"count": 3})
+ invocation = ForInvocation(id="for", collection=["item"], index=0, state=state)
+
+ result = invocation.invoke_internal_with_effects(context, _services())
+
+ assert result.output.item == "item"
+ assert len(result.effects) == 1
+ effect = result.effects[0]
+ assert isinstance(effect, ContinuationEffect)
+ assert effect.operation == "start"
+ assert effect.continuation_kind == "for"
+ assert effect.execution_ref is not None
+ assert effect.execution_ref.node_id == "for"
+ assert effect.execution_ref.frame == (4, 2)
+ assert effect.payload == {
+ "index": 0,
+ "total": 1,
+ "state": {"values": {"count": 3}},
+ }
+
+
+def test_for_return_invocation_declares_continuation_completion_effect() -> None:
+ context = _context()
+ context.execution_effects = ExecutionEffectsRecorder(source_node_id="return", frame_path=(4, 2))
+ context.execution = ExecutionInterface(context.execution_effects)
+ state = LoopState(values={"count": 4})
+ invocation = ForReturnInvocation(
+ id="return",
+ output="item",
+ state=state,
+ continue_condition=False,
+ )
+
+ result = invocation.invoke_internal_with_effects(context, _services())
+
+ assert result.output.output == "item"
+ assert result.output.state == state
+ assert len(result.effects) == 1
+ effect = result.effects[0]
+ assert isinstance(effect, ContinuationEffect)
+ assert effect.operation == "complete"
+ assert effect.continuation_kind == "for"
+ assert effect.execution_ref is not None
+ assert effect.execution_ref.node_id == "return"
+ assert effect.execution_ref.frame == (4, 2)
+ assert effect.payload == {
+ "output": "item",
+ "state": {"values": {"count": 4}},
+ "continue_condition": False,
+ }
+
+
+def test_graph_state_accepts_for_continuation_effects_without_linkage_tokens() -> None:
+ graph = Graph()
+ graph.add_node(ForInvocation(id="for", collection=["item"]))
+ graph.add_node(ForReturnInvocation(id="return"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="for", field="item"),
+ destination=EdgeConnection(node_id="return", field="output"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="for", field="loop_linkage"),
+ destination=EdgeConnection(node_id="return", field="loop_linkage"),
+ type="loop_linkage",
+ )
+ )
+ state = GraphExecutionState(graph=graph)
+
+ for_invocation = state.next()
+ assert isinstance(for_invocation, ForInvocation)
+ for_ref = state.get_execution_ref(for_invocation.id)
+ for_context = _context()
+ for_context.execution_effects = ExecutionEffectsRecorder(
+ source_node_id=for_invocation.id,
+ frame_path=for_ref.frame.iteration_path,
+ state_id=for_ref.state_id,
+ frame_id=for_ref.frame.frame_id,
+ workflow_call_depth=for_ref.frame.workflow_call_depth,
+ )
+ for_context.execution = ExecutionInterface(for_context.execution_effects)
+ for_result = for_invocation.invoke_internal_with_effects(for_context, _services())
+ state.apply(state.get_execution_ref(for_invocation.id, effect_count=len(for_result.effects)), for_result)
+
+ return_invocation = state.next()
+ assert return_invocation is not None
+ return_ref = state.get_execution_ref(return_invocation.id)
+ return_context = _context()
+ return_context.execution_effects = ExecutionEffectsRecorder(
+ source_node_id=return_invocation.id,
+ frame_path=return_ref.frame.iteration_path,
+ state_id=return_ref.state_id,
+ frame_id=return_ref.frame.frame_id,
+ workflow_call_depth=return_ref.frame.workflow_call_depth,
+ )
+ return_context.execution = ExecutionInterface(return_context.execution_effects)
+ return_result = return_invocation.invoke_internal_with_effects(return_context, _services())
+ state.apply(state.get_execution_ref(return_invocation.id, effect_count=len(return_result.effects)), return_result)
+
+ continuation = next(iter(state._generic_runtime().continuations.values()))
+ assert continuation.status == "completed"
+ assert all(token.port != "loop_linkage" for token in state.execution_tokens.values())
+ assert [effect.kind for effects in state.execution_effects.values() for effect in effects] == [
+ "continuation",
+ "continuation",
+ ]
+ snapshot = dump_execution_state(state)
+ restored = load_execution_state(snapshot)
+ assert dump_execution_state(restored)["execution_effects"] == snapshot["execution_effects"]
+
+
+ ("owner_kwargs", "message"),
+ [
+ ({"frame_path": (99,)}, "another execution frame"),
+ ({"state_id": "other"}, "another graph execution state"),
+ ({"workflow_call_depth": 1}, "another workflow-call depth"),
+ ],
+)
+def test_graph_state_rejects_continuation_effect_from_another_scope(
+ owner_kwargs: dict[str, object], message: str
+) -> None:
+ graph = Graph()
+ graph.add_node(ForInvocation(id="for", collection=["item"]))
+ graph.add_node(ForReturnInvocation(id="return"))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="for", field="item"),
+ destination=EdgeConnection(node_id="return", field="output"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="for", field="loop_linkage"),
+ destination=EdgeConnection(node_id="return", field="loop_linkage"),
+ type="loop_linkage",
+ )
+ )
+ state = GraphExecutionState(graph=graph)
+ invocation = state.next()
+ assert isinstance(invocation, ForInvocation)
+ execution_ref = state.get_execution_ref(invocation.id)
+ owner_identity: dict[str, object] = {
+ "state_id": execution_ref.state_id,
+ "frame_id": execution_ref.frame.frame_id,
+ "frame_path": execution_ref.frame.iteration_path,
+ "workflow_call_depth": execution_ref.frame.workflow_call_depth,
+ }
+ owner_identity.update(owner_kwargs)
+
+ invalid_effect = ContinuationEffect(
+ execution_ref=ExecutionRef(execution_node_id=invocation.id, **owner_identity), # type: ignore[arg-type]
+ operation="start",
+ continuation_kind="for",
+ payload={"index": 0, "total": 1, "state": {"values": {}}},
+ )
+ with pytest.raises(ValueError, match=message):
+ state.apply(execution_ref, invocation.invoke(MagicMock()), [invalid_effect])
+
+ assert not state.execution_effects
+
+
@pytest.mark.parametrize("condition", [True, False])
def test_graph_state_applies_if_activation_and_releases_selected_branch(condition: bool) -> None:
graph = Graph()