Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(execution): preserve flat loop completion durability

JPPhotod2ca52bd395c
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 189d5446f5..076abd7cfc 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -92,9 +92,10 @@ are persisted under the invocation reference. Session-built effect references ca
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. A fresh graph with exactly one static, non-empty flat `For`/`ForReturn`
pair now uses the generic scheduler adapter for readiness and continuation transitions. Graph state owns the
-invocation-specific continuation boundary: it carries returned state, honors `continue_condition`, materializes the
-next body iteration, and finalizes the aggregate. The generic scheduler remains opaque and never receives a literal
-successor node ID. Empty or input-driven collections, nested or multiple loops, and mixed control flow remain on the
+generic continuation boundary: it carries returned state, honors `continue_condition`, materializes the next body
+iteration, and finalizes the aggregate. 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 or input-driven collections, nested or multiple loops, and mixed control flow remain on the
compatibility scheduler; this additive effect seam does not claim generic scheduling for those shapes. `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
@@ -128,6 +129,14 @@ graph state unchanged.
This evidence permits the supported flat routing slice only; it does not remove
the compatibility continuation/materialization owner for unsupported shapes.
+`GraphExecutionState.complete()` remains the compatibility entry point for callers that already have a node result.
+Its first JSON-safe completion uses the same validated, atomic ledger path as `apply()`, including output tokens and
+synthetic `For`/`ForReturn` continuation effects. It still permits historical idempotent result replacement for an
+already-applied node; arbitrary in-memory values that cannot be represented in the JSON ledger remain a scheduler-only
+compatibility case and cannot be persisted. When an explicitly unversioned, partially completed legacy snapshot is
+loaded, missing flat-loop continuation buckets are synthesized before a versioned re-save so the next load remains
+valid; terminal legacy snapshots retain their legacy no-ledger compatibility.
+
`IfInvocation` now declares the same seam for branch activation: it emits one frame-scoped activation token for the
selected branch, and the graph state validates and persists it after invocation. For a fresh generic `If`, the dedicated
`_IfActivationCompiler` produces opaque, frame-local activation dependencies. `_GenericGraphSchedulerAdapter` consumes
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 6d79ef24bc..4d13cc1ade 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -197,11 +197,15 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre
- `next()` Returns the next ready exec node. If none are ready, it asks the materializer to expand more source nodes and
then retries. If the execution state is paused on a workflow call boundary, it returns `None` without scheduling more
work. Before returning a node, the runtime helper deep-copies inbound values into the node fields.
-- `complete(node_id, output)` Records the result, marks the exec node executed, marks the source node executed once all
- of its prepared exec copies are done, then decrements downstream indegrees and enqueues newly ready nodes.
+- `complete(node_id, output)` is the compatibility completion boundary. For a first JSON-safe completion it delegates
+ validation and the atomic scheduler/ledger transition to `apply()`, including output tokens and synthetic
+ continuation effects for direct `For`/`ForReturn` callers. An already-applied node retains the historical
+ idempotent result-replacement behavior; in-memory values that cannot be represented in the JSON effect ledger use
+ the scheduler-only compatibility path and are not persistable.
- `apply(execution_ref, output, effects)` validates a result against its prepared node and frame, then applies the
result through the existing scheduler while recording references, output/effect tokens, and JSON-safe effects. The
- transition and ledger update are atomic. `complete()` remains the compatibility boundary used by the scheduler.
+ transition and ledger update are atomic. Direct `complete()` callers therefore receive the same durable state for
+ supported values without changing the invocation output contract.
#### Current execution-effects seam
@@ -242,10 +246,12 @@ materialized-result fallback needed by older snapshots. This is not yet token-au
hydration, and empty-source closure; 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 ordinary
-readiness and calls the graph-state continuation boundary after each `ForReturn`. That boundary carries returned state,
-honors `continue_condition`, creates the next prepared iteration when needed, and finalizes `output_collection` and
-`final_state`. The generic scheduler receives only opaque node IDs and dependencies; it never receives a literal next
-node ID. Empty/input-driven collections and nested, multiple, or mixed loop shapes remain compatibility-owned.
+readiness and calls the graph-state generic continuation boundary after each `ForReturn`. That boundary carries returned
+state, honors `continue_condition`, creates the next prepared iteration when needed, and finalizes `output_collection`
+and `final_state`. The generic scheduler receives only opaque node IDs and dependencies; it never receives a literal
+next node ID. The compatibility continuation bridge remains available only for unsupported loop shapes and explicitly
+legacy-loaded snapshots. Empty/input-driven collections and nested, multiple, or mixed loop shapes remain
+compatibility-owned.
`ExecutionFrame` identifies the owning state, loop iteration path, and workflow-call depth. `ExecutionReference`
identifies one prepared execution node and its frame. `ExecutionToken` records an output port, value, frame, token
@@ -294,13 +300,12 @@ prepared node, while unknown references, pending-node buckets, missing executed
effects, and malformed ownership are rejected. Persisted `For` outputs are checked against prepared iteration data and,
after finalization, their authoritative returned collection and final state. Unversioned legacy snapshots retain the
compatibility loader. `For` start payloads must match the prepared index, collection total, and state before mutation. This is the invocation/effect ownership
-seam only: the legacy scheduler still resolves linkage, while the generic
-adapter's graph-state boundary creates the next prepared iteration, aggregates
-outputs, and finalizes the supported flat loop. The legacy scheduler still
-owns empty/input-driven, nested, multiple-loop, and mixed-loop
-materialization; unversioned legacy snapshots retain their compatibility
-loader. The supported fresh static flat `For`/`ForReturn` shape uses the
-generic adapter. For
+seam: the generic adapter calls the graph-state generic continuation boundary,
+which creates the next prepared iteration, aggregates outputs, and finalizes the
+supported flat loop. The compatibility bridge remains for empty/input-driven,
+nested, multiple-loop, mixed-loop, and legacy-snapshot execution; those paths
+retain their existing materialization and linkage ownership. The supported
+fresh static flat `For`/`ForReturn` shape uses the generic adapter. 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/graph.py b/invokeai/app/services/shared/graph.py
index 3523afb03c..e1344fcafe 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -33,6 +33,7 @@ from pydantic import (
TypeAdapter,
ValidationError,
field_validator,
+ model_validator,
)
from pydantic.fields import Field
from pydantic.json_schema import JsonSchemaValue
@@ -61,6 +62,8 @@ from invokeai.app.invocations.loops import (
ForReturnInvocationOutput,
LoopState,
)
+from invokeai.app.services.shared.execution_effects import ContinuationEffect
+from invokeai.app.services.shared.execution_effects import ExecutionRef as EffectExecutionRef
from invokeai.app.services.shared.execution_engine.child import (
ChildDependencyRecord,
ChildDependencyUpdate,
@@ -2253,7 +2256,7 @@ class _GenericGraphSchedulerAdapter:
raise KeyError(f"indegree missing for exec node {dependent}")
self._remove_projected(exec_node_id)
self._record_completed_node(exec_node_id, output)
- finalized_for_exec_node_id = self._state._try_schedule_next_for_iteration(exec_node_id, output)
+ finalized_for_exec_node_id = self._state._apply_generic_for_continuation(exec_node_id, output)
self._mark_source_node_complete(exec_node_id)
# A condition may become resolvable when this node completes. Resolve it
# while the state has the completed result, before recalculating generic
@@ -2859,6 +2862,16 @@ class ExecutionToken(BaseModel):
frame: ExecutionFrame = Field(description="Frame that produced the token")
value: Any = Field(description="Output port value")
token_kind: Literal["data", "activation", "stream_end"] = Field(default="data")
+
+ @model_validator(mode="before")
+ @classmethod
+ def _restore_excluded_null_value(cls, value: Any) -> Any:
+ """Allow exclude-none runtime snapshots to hydrate nullable output ports without changing the schema."""
+
+ if isinstance(value, dict) and "value" not in value:
+ return {**value, "value": None}
+ return value
+
sequence: int | None = Field(default=None, ge=0)
model_config = ConfigDict(extra="allow")
@@ -4316,6 +4329,7 @@ class GraphExecutionState(BaseModel):
_generic_child_dependencies: dict[str, ChildDependencyRecord] = PrivateAttr(default_factory=dict)
_execution_effects_persisted: bool = PrivateAttr(default=False)
_legacy_execution_snapshot: bool = PrivateAttr(default=True)
+ _legacy_snapshot_loaded: bool = PrivateAttr(default=False)
def _tx_record_once(self, key: tuple[Any, ...], undo: Callable[[], None]) -> None:
if self._apply_transaction is not None:
@@ -4587,9 +4601,22 @@ class GraphExecutionState(BaseModel):
self._get_loop_state_for_next_iteration(for_exec_node_id, return_output),
)
self._mark_loop_context_finalized(source_for_id, for_exec_node_id)
+ self._refresh_output_tokens(for_exec_node_id)
- def _try_schedule_next_for_iteration(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:
- """Advance one For continuation without making the generic scheduler know loop semantics."""
+ def _refresh_output_tokens(self, exec_node_id: str) -> None:
+ output = self.results.get(exec_node_id)
+ execution_ref = self.execution_refs.get(exec_node_id)
+ if output is None or execution_ref is None:
+ return
+ for token_id, token in self._build_execution_tokens(execution_ref, output).items():
+ existing = self.execution_tokens.get(token_id)
+ if existing is None:
+ self._tx_set_mapping(self.execution_tokens, token_id, token)
+ 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 generic flat For run."""
if not isinstance(output, ForReturnInvocationOutput):
return None
@@ -4640,9 +4667,16 @@ class GraphExecutionState(BaseModel):
self._tx_set_attr(for_node, "collection", [])
return None
+ 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)
+
def _can_use_generic_for_scheduler(self) -> bool:
"""Allow generic routing only for one flat For body with no other control-flow node."""
+ if self._legacy_snapshot_loaded:
+ return False
if any(
isinstance(node, (IterateInvocation, CollectInvocation, IfInvocation, CallSavedWorkflowInvocation))
for node in self.graph.nodes.values()
@@ -4989,9 +5023,7 @@ class GraphExecutionState(BaseModel):
self._tx_set_attr(continuation, "payload", copydeep(payload))
elif isinstance(node, ForReturnInvocation) and operation == "complete":
expected_payload = self._prepared_for_continuation_payload(node)
- if expected_payload is not None and self._continuation_payload_key(
- payload
- ) != self._continuation_payload_key(expected_payload):
+ if expected_payload is not None and not self._for_return_payloads_match(payload, expected_payload):
raise ValueError("completed continuation payload does not match ForReturn output")
for_exec_node_id = self._get_for_parent(execution_ref.exec_node_id)
if for_exec_node_id is None:
@@ -5022,6 +5054,26 @@ class GraphExecutionState(BaseModel):
normalized = cls._normalize_continuation_payload(payload)
return json.dumps(normalized, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
+ @classmethod
+ def _payload_values_match(cls, left: Any, right: Any) -> bool:
+ try:
+ return cls._continuation_payload_key(left) == cls._continuation_payload_key(right)
+ except ValueError:
+ try:
+ return left is right or left == right
+ except Exception:
+ return False
+
+ @classmethod
+ def _for_return_payloads_match(cls, left: Any, right: Any) -> bool:
+ """Compare durable return identity while allowing the returned loop state to be computed by the node."""
+
+ if not isinstance(left, dict) or not isinstance(right, dict):
+ return cls._payload_values_match(left, right)
+ return cls._payload_values_match(left.get("output"), right.get("output")) and left.get(
+ "continue_condition"
+ ) == right.get("continue_condition")
+
@classmethod
def _for_start_continuation_payload(
cls, node: ForInvocation, output: ForInvocationOutput | None = None
@@ -5113,9 +5165,7 @@ class GraphExecutionState(BaseModel):
actual_payload = self._for_start_continuation_payload(node, output)
if self._continuation_payload_key(actual_payload) != self._continuation_payload_key(expected_payload):
raise ValueError("For output does not match prepared For")
- if self._continuation_payload_key(output.item) != self._continuation_payload_key(
- self._for_item_for_validation(node)
- ):
+ if not self._payload_values_match(output.item, self._for_item_for_validation(node)):
raise ValueError("For output item does not match prepared For")
source_node_id = self.prepared_source_mapping.get(node.id)
parent_iteration_path = self._get_for_parent_iteration_path(node.id)
@@ -5161,7 +5211,7 @@ class GraphExecutionState(BaseModel):
elif isinstance(node, ForReturnInvocation) and isinstance(output, ForReturnInvocationOutput):
expected_payload = self._prepared_for_continuation_payload(node)
actual_payload = self._for_return_continuation_payload(node, output)
- if self._continuation_payload_key(actual_payload) != self._continuation_payload_key(expected_payload):
+ if not self._for_return_payloads_match(actual_payload, expected_payload):
raise ValueError("ForReturn output does not match prepared ForReturn")
def _requires_continuation_effect(self, execution_ref: ExecutionReference) -> bool:
@@ -5173,6 +5223,33 @@ class GraphExecutionState(BaseModel):
output = self.results.get(execution_ref.exec_node_id)
return isinstance(output, ForInvocationOutput) and output.total > 0
+ def _build_compatibility_continuation_effect(
+ self, execution_ref: ExecutionReference, output: BaseInvocationOutput
+ ) -> ContinuationEffect:
+ node = self.execution_graph.get_node(execution_ref.exec_node_id)
+ if isinstance(node, ForInvocation) and isinstance(output, ForInvocationOutput):
+ operation = "start"
+ payload = self._for_start_continuation_payload(node, output)
+ elif isinstance(node, ForReturnInvocation) and isinstance(output, ForReturnInvocationOutput):
+ operation = "complete"
+ payload = self._for_return_continuation_payload(node, output)
+ else:
+ raise TypeError("Compatibility continuation effects require a For or ForReturn output")
+
+ effect_ref = EffectExecutionRef(
+ execution_node_id=execution_ref.exec_node_id,
+ state_id=execution_ref.state_id,
+ frame_path=execution_ref.frame.iteration_path,
+ frame_id=execution_ref.frame.frame_id,
+ workflow_call_depth=execution_ref.frame.workflow_call_depth,
+ )
+ return ContinuationEffect(
+ execution_ref=effect_ref,
+ operation=operation,
+ continuation_kind="for",
+ payload=payload,
+ )
+
def _complete_for_continuation(self, for_exec_node_id: str, result: Any) -> None:
result = self._normalize_continuation_payload(result)
continuation = self._for_continuation(for_exec_node_id)
@@ -5853,6 +5930,11 @@ class GraphExecutionState(BaseModel):
require_continuation = effects is not None or effect_count is not None
if effects is None:
effect_values = []
+ if effect_count is None and isinstance(
+ self.execution_graph.get_node(ref.exec_node_id), (ForInvocation, ForReturnInvocation)
+ ):
+ effect_values = [self._build_compatibility_continuation_effect(ref, output_value)]
+ require_continuation = True
else:
batch_values = self._value_from_object(effects, "effects")
effect_values = list(batch_values if batch_values is not None else effects)
@@ -5862,7 +5944,6 @@ class GraphExecutionState(BaseModel):
effect_count,
require_continuation=require_continuation,
)
- tokens = self._build_execution_tokens(ref, output_value, effect_values)
persisted_effects = copydeep(effect_values)
# All validation above is side-effect free. Preserve complete() as the scheduler compatibility boundary,
@@ -5874,7 +5955,8 @@ class GraphExecutionState(BaseModel):
# Capture and record the continuation before scheduler completion can clear the prepared For
# collection or otherwise mutate the node used to validate its durable payload.
self._record_continuation_effects(ref, effect_values)
- finalized_outputs = self.complete(ref.exec_node_id, output_value)
+ finalized_outputs = self._complete(ref.exec_node_id, output_value)
+ tokens = self._build_execution_tokens(ref, output_value, effect_values)
self._record_effect_streams(ref, effect_values)
ref.effect_count = len(effect_values)
self._tx_set_mapping(self.execution_refs, ref.exec_node_id, ref)
@@ -6237,6 +6319,25 @@ class GraphExecutionState(BaseModel):
effect_count = existing.effect_count if existing is not None else None
self.execution_refs[exec_node_id] = self._expected_execution_ref(exec_node_id, effect_count=effect_count)
+ def _synthesize_legacy_execution_effects(self) -> None:
+ """Upgrade completed legacy For results with the v1 continuation records needed for the next dump."""
+
+ if not self._legacy_snapshot_loaded or all(
+ source_node_id in self.executed for source_node_id in self.graph.nodes
+ ):
+ return
+ for exec_node_id, output in self.results.items():
+ execution_ref = self.execution_refs.get(exec_node_id)
+ if execution_ref is None or execution_ref.reference_id in self.execution_effects:
+ continue
+ if not self._requires_continuation_effect(execution_ref):
+ continue
+ if not isinstance(output, (ForInvocationOutput, ForReturnInvocationOutput)):
+ continue
+ effect = self._build_compatibility_continuation_effect(execution_ref, output)
+ self.execution_effects[execution_ref.reference_id] = [effect]
+ execution_ref.effect_count = 1
+
def _rehydrate_generic_runtime_state(self) -> None:
"""Rebuild private stream/continuation adapters from durable results."""
@@ -6337,7 +6438,9 @@ class GraphExecutionState(BaseModel):
if isinstance(__context, dict) and "execution_effects_persisted" in __context:
self._execution_effects_persisted = __context["execution_effects_persisted"]
self._legacy_execution_snapshot = __context.get("legacy_execution_snapshot", False)
+ self._legacy_snapshot_loaded = self._legacy_execution_snapshot
self._rehydrate_execution_refs()
+ self._synthesize_legacy_execution_effects()
self._rehydrate_runtime_state()
model_config = ConfigDict(
@@ -6392,7 +6495,37 @@ class GraphExecutionState(BaseModel):
return next_node
def complete(self, node_id: str, output: BaseInvocationOutput) -> list[tuple[BaseInvocation, BaseInvocationOutput]]:
- """Marks a node as complete"""
+ """Validate and apply a direct compatibility completion through the execution ledger."""
+
+ if self._apply_transaction is None:
+ execution_ref = self.get_execution_ref(node_id)
+ if execution_ref.exec_node_id in self.executed or execution_ref.reference_id in self.execution_effects:
+ # Historical callers may replace a result after invoking a node directly. The scheduler has
+ # already applied its transition, so preserve that idempotent result-replacement contract.
+ return self._complete(node_id, output)
+ if isinstance(output, ForInvocationOutput):
+ try:
+ self._normalize_continuation_payload(output.item)
+ except ValueError:
+ # In-memory compatibility callers may use arbitrary collection values. Such results cannot
+ # enter the JSON execution ledger, but must retain the old scheduler behavior.
+ return self._complete(node_id, output)
+ if isinstance(output, ForReturnInvocationOutput):
+ return_node = self.execution_graph.get_node(execution_ref.exec_node_id)
+ if isinstance(return_node, ForReturnInvocation):
+ try:
+ self._normalize_continuation_payload(return_node.output)
+ except ValueError:
+ # A return connected to a non-JSON in-memory value has the same non-persistable constraint.
+ return self._complete(node_id, output)
+ return self.apply(execution_ref, output)
+ return self._complete(node_id, output)
+
+ def _complete(
+ self, node_id: str, output: BaseInvocationOutput
+ ) -> list[tuple[BaseInvocation, BaseInvocationOutput]]:
+ """Apply a result after the caller has established the transaction and ledger boundary."""
+
finalized_outputs = self._scheduler().complete(node_id, output)
if self._mark_completed_sources():
self.execution_graph._invalidate_edge_indexes()
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 28f8888d6c..0dd401cfa2 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -813,6 +813,73 @@ def test_flat_for_fresh_execution_matches_compatibility_scheduler() -> None:
assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)
+def test_flat_for_generic_path_does_not_use_compatibility_continuation_bridge(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def fail_compatibility_bridge(*_: object, **__: object) -> None:
+ raise AssertionError("generic For execution used the compatibility continuation bridge")
+
+ monkeypatch.setattr(GraphExecutionState, "_try_schedule_next_for_iteration", fail_compatibility_bridge)
+
+ 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]
+
+
+def test_direct_flat_for_completion_persists_continuations_and_final_tokens() -> None:
+ trace, state = _run(GraphExecutionState(graph=_flat_for_graph()))
+
+ assert trace == ["for", "body", "return", "for", "body", "return"]
+ snapshot = dump_execution_state(state)
+ restored = load_execution_state(snapshot)
+ final_for_id = max(
+ state.source_prepared_mapping["for"],
+ key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,
+ )
+ final_ref = state.execution_refs[final_for_id]
+ final_output = state.results[final_for_id]
+ output_collection_token_id = f"{final_ref.reference_id}:output_collection"
+ final_state_token_id = f"{final_ref.reference_id}:final_state"
+
+ assert snapshot["execution_effects"]
+ assert state.execution_tokens[output_collection_token_id].value == final_output.output_collection == [11, 12]
+ assert state.execution_tokens[final_state_token_id].value == final_output.final_state
+ assert restored.execution_tokens[output_collection_token_id].value == [11, 12]
+ assert restored.execution_tokens[final_state_token_id].value == final_output.final_state.model_dump(mode="json")
+ assert sorted(
+ (effect.operation, effect.continuation_kind)
+ for effects in state.execution_effects.values()
+ for effect in effects
+ if effect.kind == "continuation"
+ ) == [("complete", "for"), ("complete", "for"), ("start", "for"), ("start", "for")]
+ assert restored.is_complete()
+
+
+def test_legacy_flat_for_snapshot_uses_compatibility_scheduler() -> None:
+ _trace, partial_state = _run_graph_with_effects(
+ GraphExecutionState(graph=_flat_for_graph()),
+ stop_after=1,
+ )
+ snapshot = dump_execution_state(partial_state)
+ snapshot.pop("execution_state_version")
+ snapshot.pop("execution_effects")
+
+ restored = load_execution_state(snapshot)
+ migrated = load_execution_state(dump_execution_state(restored))
+
+ assert isinstance(restored._scheduler(), _ExecutionScheduler)
+ remaining_trace, restored = _run(restored)
+ migrated_trace, migrated = _run(migrated)
+ assert remaining_trace == ["body", "return", "for", "body", "return"]
+ assert migrated_trace == remaining_trace
+ assert restored.is_complete()
+ assert migrated.is_complete()
+ assert _final_for_output(restored).output_collection == [11, 12]
+ assert _final_for_output(migrated).output_collection == [11, 12]
+
+
def test_flat_for_fresh_execution_releases_after_loop_consumer() -> None:
generic_trace, generic_state = _run_graph_with_effects(
GraphExecutionState(graph=_flat_for_graph(with_after=True)),