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
fix(execution): harden legacy loop migration
JPPhoto99bcf20eca8d
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex 076abd7cfc..9fd147d1e0 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -135,7 +135,8 @@ synthetic `For`/`ForReturn` continuation effects. It still permits historical idalready-applied node; arbitrary in-memory values that cannot be represented in the JSON ledger remain a scheduler-onlycompatibility case and cannot be persisted. When an explicitly unversioned, partially completed legacy snapshot isloaded, 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.+valid. A loaded terminal legacy state may retain its empty in-memory ledger for compatibility, but+`dump_execution_state()` upgrades missing loop buckets in the versioned snapshot.`IfInvocation` now declares the same seam for branch activation: it emits one frame-scoped activation token for theselected branch, and the graph state validates and persists it after invocation. For a fresh generic `If`, the dedicateddiff --git a/invokeai/app/services/shared/execution_state_migration.py b/invokeai/app/services/shared/execution_state_migration.pyindex 1edd020d95..850743cb22 100644--- a/invokeai/app/services/shared/execution_state_migration.py+++ b/invokeai/app/services/shared/execution_state_migration.py@@ -36,6 +36,10 @@ def dump_execution_state(state: GraphExecutionState) -> dict[str, Any]:# public model/schema, but an output port may legitimately carry None and the general# exclude_none policy would otherwise make the snapshot impossible to hydrate._retain_nullable_execution_token_values(snapshot)+ for reference_id, effects in state._legacy_execution_effects_for_snapshot().items():+ snapshot.setdefault("execution_effects", {})[reference_id] = [+ effect.model_dump(mode="json") if hasattr(effect, "model_dump") else effect for effect in effects+ ]snapshot["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSIONreturn snapshotdiff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex e1344fcafe..e49f91d7ad 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -4999,7 +4999,13 @@ class GraphExecutionState(BaseModel):continuation.start()return continuation- def _record_continuation_effects(self, execution_ref: ExecutionReference, effects: Iterable[Any]) -> None:+ def _record_continuation_effects(+ self,+ execution_ref: ExecutionReference,+ effects: Iterable[Any],+ *,+ allow_return_state_override: bool = False,+ ) -> None:"""Reconcile durable For continuation effects with the private runtime record."""node = self.execution_graph.get_node(execution_ref.exec_node_id)@@ -5023,7 +5029,9 @@ 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 not self._for_return_payloads_match(payload, expected_payload):+ if expected_payload is not None and not self._for_return_payloads_match(+ payload, expected_payload, allow_state_override=allow_return_state_override+ ):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:@@ -5065,14 +5073,16 @@ class GraphExecutionState(BaseModel):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."""+ def _for_return_payloads_match(cls, left: Any, right: Any, *, allow_state_override: bool = False) -> bool:+ """Compare durable return identity, optionally allowing compatibility callers to replace loop state."""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")+ if not cls._payload_values_match(left.get("output"), right.get("output")):+ return False+ if left.get("continue_condition") != right.get("continue_condition"):+ return False+ return allow_state_override or cls._payload_values_match(left.get("state"), right.get("state"))@classmethoddef _for_start_continuation_payload(@@ -5157,7 +5167,11 @@ class GraphExecutionState(BaseModel):return collection[node.index]def _validate_for_continuation_output(- self, execution_ref: ExecutionReference, output: BaseInvocationOutput+ self,+ execution_ref: ExecutionReference,+ output: BaseInvocationOutput,+ *,+ allow_return_state_override: bool = False,) -> None:node = self.execution_graph.get_node(execution_ref.exec_node_id)if isinstance(node, ForInvocation) and isinstance(output, ForInvocationOutput):@@ -5211,7 +5225,9 @@ 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 not self._for_return_payloads_match(actual_payload, expected_payload):+ if not self._for_return_payloads_match(+ actual_payload, expected_payload, allow_state_override=allow_return_state_override+ ):raise ValueError("ForReturn output does not match prepared ForReturn")def _requires_continuation_effect(self, execution_ref: ExecutionReference) -> bool:@@ -5909,6 +5925,7 @@ class GraphExecutionState(BaseModel):effects: Optional[Iterable[Any]] = None,*,effect_count: Optional[int] = None,+ _compatibility_completion: bool = False,) -> list[tuple[BaseInvocation, BaseInvocationOutput]]:"""Apply output/effects through current scheduler while retaining old ``complete()`` behavior."""@@ -5926,7 +5943,7 @@ class GraphExecutionState(BaseModel):if effects is None:effects = result_effectsoutput_value = self._validate_output_owner(ref, output)- self._validate_for_continuation_output(ref, output_value)+ self._validate_for_continuation_output(ref, output_value, allow_return_state_override=_compatibility_completion)require_continuation = effects is not None or effect_count is not Noneif effects is None:effect_values = []@@ -5954,7 +5971,7 @@ class GraphExecutionState(BaseModel):try:# 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)+ self._record_continuation_effects(ref, effect_values, allow_return_state_override=_compatibility_completion)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)@@ -6338,6 +6355,24 @@ class GraphExecutionState(BaseModel):self.execution_effects[execution_ref.reference_id] = [effect]execution_ref.effect_count = 1+ def _legacy_execution_effects_for_snapshot(self) -> dict[str, list[Any]]:+ """Return missing loop effects needed to convert any loaded legacy state on its next dump."""++ if not self._legacy_snapshot_loaded:+ return {}+ effects: dict[str, list[Any]] = {}+ 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 isinstance(output, (ForInvocationOutput, ForReturnInvocationOutput)):+ effects[execution_ref.reference_id] = [+ self._build_compatibility_continuation_effect(execution_ref, output)+ ]+ return effects+def _rehydrate_generic_runtime_state(self) -> None:"""Rebuild private stream/continuation adapters from durable results."""@@ -6498,7 +6533,17 @@ class GraphExecutionState(BaseModel):"""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)+ existing_ref = self.execution_refs.get(node_id)+ execution_ref = self._expected_execution_ref(+ node_id, effect_count=existing_ref.effect_count if existing_ref is not None else None+ )+ if existing_ref is not None and (+ existing_ref.reference_id not in ("", execution_ref.reference_id)+ or existing_ref.state_id not in ("", execution_ref.state_id)+ or existing_ref.exec_node_id not in ("", execution_ref.exec_node_id)+ or existing_ref.source_node_id not in ("", execution_ref.source_node_id)+ ):+ raise ValueError(f"Execution reference for {node_id} does not belong to this state")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.@@ -6518,7 +6563,7 @@ class GraphExecutionState(BaseModel):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.apply(execution_ref, output, _compatibility_completion=True)return self._complete(node_id, output)def _complete(diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.pyindex 24268698bc..6c943af87a 100644--- a/tests/app/services/shared/test_execution_effects.py+++ b/tests/app/services/shared/test_execution_effects.py@@ -511,6 +511,29 @@ def test_graph_state_rejects_forged_for_return_output_with_matching_completion_eassert dump_execution_state(state) == before+def test_graph_state_rejects_forged_for_return_state_with_matching_completion_effect() -> None:+ state, return_ref, return_result = _apply_flat_for_pair(["item"], apply_return=False)+ effect = return_result.effects[0]+ assert isinstance(effect, ContinuationEffect)+ forged_state = LoopState(values={"forged": True})+ forged_output = return_result.output.model_copy(update={"state": forged_state})+ forged_effect = effect.model_copy(+ deep=True,+ update={"payload": {**effect.payload, "state": forged_state.model_dump(mode="json")}},+ )+ before = dump_execution_state(state)++ with pytest.raises(ValueError, match="ForReturn output does not match prepared ForReturn"):+ state.apply(+ return_ref,+ InvocationRunResult(output=forged_output, effects=return_result.effects),+ [forged_effect],+ effect_count=1,+ )++ assert dump_execution_state(state) == before++def test_graph_state_rejects_forged_for_item_with_valid_continuation_fields() -> None:graph = Graph()graph.add_node(ForInvocation(id="for", collection=["item"]))diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 0dd401cfa2..ca16dc843b 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -11,7 +11,7 @@ from pydantic import ValidationErrorfrom invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation, LoopState, StateSetInvocationfrom invokeai.app.invocations.math import AddInvocation-from invokeai.app.invocations.primitives import BooleanInvocation+from invokeai.app.invocations.primitives import BooleanInvocation, BooleanOutputfrom invokeai.app.services.shared import graph as graph_modulefrom invokeai.app.services.shared.execution_state_migration import (CURRENT_EXECUTION_STATE_VERSION,@@ -810,6 +810,44 @@ def test_flat_for_fresh_execution_matches_compatibility_scheduler() -> None:for exec_node_id, source_node_id in generic_state.prepared_source_mapping.items()if source_node_id == "for"}+ expected_continuations = [+ (+ (0,),+ "completed",+ {"index": 0, "total": 2, "state": {"values": {}}},+ {"output": 11, "state": None, "continue_condition": True},+ ),+ (+ (1,),+ "completed",+ {"index": 1, "total": 2, "state": {"values": {}}},+ {"output": 12, "state": None, "continue_condition": True},+ ),+ ]+ expected_effects = [+ ("start", {"index": 0, "total": 2, "state": {"values": {}}}),+ ("complete", {"output": 11, "state": None, "continue_condition": True}),+ ("start", {"index": 1, "total": 2, "state": {"values": {}}}),+ ("complete", {"output": 12, "state": None, "continue_condition": True}),+ ]+ for state in (generic_state, compatibility_state):+ assert [+ (tuple(continuation.frame.iteration_path), continuation.status, continuation.payload, continuation.result)+ for continuation in sorted(+ state._generic_runtime().continuations.values(),+ key=lambda continuation: continuation.frame.iteration_path,+ )+ ] == expected_continuations+ actual_effects = [+ (effect.operation, effect.payload)+ for effects in state.execution_effects.values()+ for effect in effects+ if effect.kind == "continuation"+ ]+ assert sorted(actual_effects, key=lambda item: (item[0], json.dumps(item[1], sort_keys=True))) == sorted(+ expected_effects, key=lambda item: (item[0], json.dumps(item[1], sort_keys=True))+ )+ assert _final_for_output(state).output_collection == [11, 12]assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)@@ -880,6 +918,34 @@ def test_legacy_flat_for_snapshot_uses_compatibility_scheduler() -> None:assert _final_for_output(migrated).output_collection == [11, 12]+def test_terminal_legacy_flat_for_snapshot_can_be_resaved_and_reloaded() -> None:+ _trace, state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()))+ snapshot = dump_execution_state(state)+ snapshot.pop("execution_state_version")+ snapshot.pop("execution_effects")++ restored = load_execution_state(snapshot)+ migrated = load_execution_state(dump_execution_state(restored))++ assert restored.execution_effects == {}+ assert migrated.is_complete()+ assert _final_for_output(migrated).output_collection == [11, 12]+++def test_failed_direct_completion_does_not_persist_a_reference() -> None:+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert isinstance(node, AddInvocation)+ before = dump_execution_state(state)++ with pytest.raises(TypeError, match="does not belong to execution node"):+ state.complete(node.id, BooleanOutput(value=True))++ assert dump_execution_state(state) == before++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)),