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
test(execution): harden flat loop compatibility boundary
JPPhoto132494a0bcfb
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex f021048fdf..fe790994a9 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -106,6 +106,28 @@ for the canonical stream to close, and completion mirrors Iterate outputs into tMaterialization still owns copy expansion, iteration paths, grouping, and explicit empty closure; mixed control-flow andqueue lifecycle remain compatibility-owned. `loop_linkage` remains association metadata and never becomes a data token.+The supported flat-loop differential gate covers generic/compatibility parity+for successful execution, carried and replaced state, early break, empty and+input-driven fallback routing, `None` output items, body/return failure,+partial rehydration, frame identity, and SQLite cancellation/retry isolation.+Continuation effects are normalized to JSON values and validated before+mutation: exact duplicate effects in one batch are retained once, while+conflicting terminal payloads (including type-distinct JSON values) are+rejected. Before scheduler completion, `ForInvocationOutput` and+`ForReturnInvocationOutput` continuation fields must match their prepared nodes;+the `For` item must match its prepared collection item, and effects must+independently match those values. Current versioned snapshots must include an+execution-effect ledger: every ledger key must name an executed prepared node,+and pending nodes, unknown references, missing executed markers, missing+continuation effects, and malformed ownership are rejected. Persisted `For`+outputs are checked against prepared iteration data and, after finalization,+the authoritative returned collection and final state. Unversioned legacy+snapshots retain their compatibility loader. A `For` start effect must match+the prepared index, collection total, and state; malformed effects leave the+graph state unchanged.+This evidence permits the supported flat routing slice only; it does not remove+the compatibility continuation/materialization owner for unsupported shapes.+`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 dedicated`_IfActivationCompiler` produces opaque, frame-local activation dependencies. `_GenericGraphSchedulerAdapter` consumes@@ -116,8 +138,8 @@ edges. Forced `_ExecutionScheduler` still retains`_IfBranchScheduler` legacy topology, input-edge pruning, and skip behavior for compatibility snapshots. `apply()`replaces the activation token by stable identity, and activation effects are excluded from stream handling. This is anownership seam, not final removal of all legacy topology. Author-time activation ports and literal successor IDs remain-absent, while loop and saved-workflow control flow remain on their compatibility paths until differential coverage-proves their generic replacements.+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 orinput-driven `For`, nested/mixed control flow, and existing snapshots. Ordinary static DAGs, legacy-shaped `If` graphs,@@ -127,8 +149,8 @@ generic `If` uses the compiler/adapter seam described above. This is intentionalthe generic records preserve tested loop semantics first, while the old execution graph remains the fallback for controllowerings, legacy snapshots, and unsupported mixed loop shapes. No activation or stream ports are added to author-timegraph JSON.-This migration does not modify code under `invokeai/frontend/...`; the existing frontend/backend external interface-remains frozen. The ownership seam does not remove all legacy topology yet.+This migration does not modify any file under `invokeai/frontend/...`, including generated schemas; the existing+frontend/backend external interface remains frozen. The ownership seam does not remove all legacy topology yet.The frontend and backend validate the same boundary rules. Saved workflows preserve node types, field handles, and thedirect linkage edge. The current invocation templates provide output-scope metadata when a workflow is loaded. Thediff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.pyindex ec5b9d0318..7a5f47a7e6 100644--- a/invokeai/app/services/session_processor/session_processor_default.py+++ b/invokeai/app/services/session_processor/session_processor_default.py@@ -214,11 +214,9 @@ class DefaultSessionRunner(SessionRunnerBase):# use the cancel event to check if the session is canceled.session_finished = queue_item.session.is_complete()already_terminal = self._is_canceled() or queue_item.status in ["failed", "canceled", "completed"]- if session_finished or already_terminal:- # Last pass, so the check at the top will not run again — which leaves the- # node that just ran, the only node of a one-node graph, as the one node- # nothing re-checks. A revocation committed while it executed would- # otherwise let the item be recorded as completed.+ if session_finished:+ # Re-check ownership after the final node. The next pass still lets the scheduler+ # materialize any downstream node that became ready while finalizing a loop.## Deliberately narrow, because after a node the balance is the reverse of# what it is before one: there is no execution left to refuse, only a@@ -228,8 +226,13 @@ class DefaultSessionRunner(SessionRunnerBase):# down with it — and it does not fail closed (see `queue_owner_is_active`).# A suspended workflow call is not `is_complete()`, so it is untouched here# and re-checked when the parent resumes.- if session_finished and not already_terminal and not queue_item.session.has_error():- self._cancel_if_owner_revoked(queue_item, unreadable_is_active=True)+ if session_finished and not queue_item.session.has_error():+ if self._cancel_if_owner_revoked(queue_item, unreadable_is_active=True):+ break+ if not already_terminal:+ continue++ if already_terminal:breakdef _cancel_if_owner_revoked(self, queue_item: SessionQueueItem, *, unreadable_is_active: bool = False) -> bool:@@ -524,6 +527,10 @@ class DefaultSessionRunner(SessionRunnerBase):)self._services.logger.error(error_traceback)+ # Keep the live session for the invocation error event. Terminal queue persistence may clean up prepared+ # execution mappings, but the event still needs the source id for the invocation that failed.+ event_queue_item = queue_item+# Fail the queue itemqueue_item = self._services.session_queue.set_queue_item_session(queue_item.item_id, queue_item.session)queue_item = self._services.session_queue.fail_queue_item(@@ -532,7 +539,7 @@ class DefaultSessionRunner(SessionRunnerBase):# Send error eventself._services.events.emit_invocation_error(- queue_item=queue_item,+ queue_item=event_queue_item,invocation=invocation,error_type=error_type,error_message=error_message,diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 748221d92f..1da630621c 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -31,8 +31,8 @@ authorized child-dependency records are stored in`invokeai.app.services.shared.execution_engine`; legacy graph and queue behavior is retained behind adapters whilethose records become authoritative one behavior at a time.-This refactoring is backend-only. No code under `invokeai/frontend/...` may be changed, and the existing frontend/backend-external interface remains frozen; generated schemas may change only for additive optional runtime response metadata.+This refactoring is backend-only. No file under `invokeai/frontend/...` may be changed, including generated schemas. The+existing frontend/backend external interface remains frozen; any required schema or client change is a separate project.## 2) Major Data Types@@ -270,10 +270,13 @@ subclasses that declare frame-scoped data, activation, stream-closure, child,and terminal effects. The generic scheduler selects nodes from requiredeffects for the current frame; it never receives a literal successor-node ID.Current implementation is narrower: `IfInvocation` and non-empty-`IterateInvocation` use the effect recorder for activation and stream effects.+`IterateInvocation` use the effect recorder for activation and stream effects;+the supported static, non-empty flat `For`/`ForReturn` shape uses it for+frame-scoped continuation effects and generic readiness/continuation+projection.Direct `Iterate`/`Collect`-only graphs use the generic scheduler adapter forreadiness and completion, while the materializer still expands copies and-groups paths. `For`, `ForReturn`, workflow-call invocations, and mixed+groups paths. Workflow-call invocations, unsupported loop shapes, and mixedcontrol-flow graphs remain on compatibility paths. `ForInvocation` and`ForReturnInvocation` now declare one validated, frame-scoped `continuation`effect per prepared invocation: `For` starts the `for` continuation with its@@ -282,35 +285,52 @@ continue-decision data. Session-built recorders bind the effect reference tothe graph-state ID, durable frame ID, iteration path, and workflow-call depth;graph-state validation rejects a stale or cross-frame continuation beforemutation. 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+and excludes `loop_linkage` from token data. Continuation payloads are+normalized to JSON values before runtime or durable comparison. Exact+duplicate continuation effects in one batch are idempotently retained once;+conflicting terminal payloads, including type-distinct JSON values, are+rejected transactionally. Before `complete()` mutates scheduler state, `ForInvocationOutput`+and `ForReturnInvocationOutput` continuation fields must match their prepared nodes;+the `For` item must match its prepared collection item, and continuation effects must independently match those+prepared values. Current versioned snapshots require an execution-effect ledger: each bucket must belong to an executed+prepared node, while unknown references, pending-node buckets, missing executed markers, missing required continuation+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`If`, generic readiness consumes opaque frame-local plan dependencies and requiresboth matching private `ActivationGate` runtime state and a persisted activation token;generic resolution retires unselected prepared nodes through scheduler discard. The forced compatibility`_ExecutionScheduler` path retains `_IfBranchScheduler` topology, edge-prune, and skip behavior.This is not token-built successor topology. Loop and workflow-call adapters-still own materialization and durable queue lifecycle. Those owners may be-removed only after differential tests cover fresh, partially completed,+still own materialization for unsupported shapes and durable queue lifecycle.+Those owners may be removed only after differential tests cover fresh, partially completed,rehydrated, failed, canceled, and retried sessions. The frontend boundaryremains frozen: this refactoring does not modify `invokeai/frontend/...` orexisting web/webv2 interactions.The test-only differential harness at`tests/app/services/shared/test_execution_engine_differential.py` compares-generic and forced-compatibility scheduling for static DAGs and a constructed-mixed/nested `If` graph. Its fixture corpus covers fresh completion, true/false-branch selection, nested branch isolation, partial checkpoints, versioned-rehydration, in-flight claim replay, activation-token persistence, and injected-failure. The `If` comparison includes strict source-level results, executed-history, errors, terminal state, and normalized indegrees; compatibility skip-propagation must not leave stale downstream indegrees. Both scheduler adapters-expose the same skip transition; the legacy path releases downstream indegrees-without trying to hydrate inputs from the skipped node. It intentionally does-not claim durable persistence of the generic scheduler's private claim set, nor-does it cover loop or workflow-call ownership migration. Real queue/processor+generic and forced-compatibility scheduling for static DAGs, a constructed+mixed/nested `If` graph, and the supported static flat `For`/`ForReturn` shape.+Its fixture corpus covers fresh completion, true/false branch selection, nested+branch isolation, partial checkpoints, versioned rehydration, in-flight claim+replay, activation-token persistence, injected failure, loop continuation,+carried state, early break, output `None`, cancellation/retry isolation, and+continuation/effect integrity. The `If` comparison includes strict source-level+results, executed history, errors, terminal state, and normalized indegrees;+compatibility skip propagation must not leave stale downstream indegrees. Both+scheduler adapters expose the same skip transition; the legacy path releases+downstream indegrees without trying to hydrate inputs from the skipped node. It+does not claim durable persistence of the generic scheduler's private claim set,+nor does it claim ownership migration for empty/input-driven, nested, multiple,+mixed, or workflow-call loop shapes. Real queue/processorcoverage in `tests/app/services/session_processor/test_if_processor_sqlite.py`also exercises true and false `If` selection, cancellation before and afterresolution, retry from a canceled SQLite item, fresh execution identities, anddiff --git a/invokeai/app/services/shared/execution_state_migration.py b/invokeai/app/services/shared/execution_state_migration.pyindex 4b54688903..1edd020d95 100644--- a/invokeai/app/services/shared/execution_state_migration.py+++ b/invokeai/app/services/shared/execution_state_migration.py@@ -86,6 +86,8 @@ def load_execution_state(snapshot: Mapping[str, Any]) -> GraphExecutionState:f"{CURRENT_EXECUTION_STATE_VERSION}")migrated_payload = payload+ legacy_execution_snapshot = version == LEGACY_EXECUTION_STATE_VERSION+ execution_effects_persisted = "execution_effects" in migrated_payload and not legacy_execution_snapshotwhile version < CURRENT_EXECUTION_STATE_VERSION:migrate = _SNAPSHOT_MIGRATIONS.get(version)if migrate is None:@@ -101,4 +103,11 @@ def load_execution_state(snapshot: Mapping[str, Any]) -> GraphExecutionState:f"Execution state snapshot version {version} is unsupported; current version is "f"{CURRENT_EXECUTION_STATE_VERSION}")- return GraphExecutionState.model_validate(migrate(migrated_payload), strict=False)+ return GraphExecutionState.model_validate(+ migrate(migrated_payload),+ strict=False,+ context={+ "execution_effects_persisted": execution_effects_persisted,+ "legacy_execution_snapshot": legacy_execution_snapshot,+ },+ )diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex df92c704ac..fa6a3900cb 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -2,6 +2,7 @@import copyimport itertools+import jsonimport weakreffrom collections import dequefrom dataclasses import dataclass@@ -4397,6 +4398,8 @@ class GraphExecutionState(BaseModel):_generic_execution_runtime: Optional[ExecutionEngineRuntime] = PrivateAttr(default=None)_generic_graph_scheduler: Optional[_GenericGraphSchedulerAdapter] = PrivateAttr(default=None)_generic_child_dependencies: dict[str, ChildDependencyRecord] = PrivateAttr(default_factory=dict)+ _execution_effects_persisted: bool = PrivateAttr(default=False)+ _legacy_execution_snapshot: bool = PrivateAttr(default=True)def _tx_record_once(self, key: tuple[Any, ...], undo: Callable[[], None]) -> None:if self._apply_transaction is not None:@@ -4690,16 +4693,19 @@ class GraphExecutionState(BaseModel):for_node = self.execution_graph.get_node(for_exec_node_id)if not isinstance(for_node, ForInvocation):return None+ for_return_node = self.execution_graph.get_node(exec_node_id)+ assert isinstance(for_return_node, ForReturnInvocation)- self._complete_for_continuation(for_exec_node_id, output.model_dump(mode="json"))+ self._complete_for_continuation(+ for_exec_node_id,+ self._for_return_continuation_payload(for_return_node, output),+ )registry = self._prepared_registry()source_for_id = registry.get_source_node_id(for_exec_node_id)source_return_id = registry.get_source_node_id(exec_node_id)next_index = for_node.index + 1- for_return_node = self.execution_graph.get_node(exec_node_id)- assert isinstance(for_return_node, ForReturnInvocation)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(@@ -5049,16 +5055,229 @@ class GraphExecutionState(BaseModel):continuation.start()return continuation+ def _record_continuation_effects(self, execution_ref: ExecutionReference, effects: Iterable[Any]) -> None:+ """Reconcile durable For continuation effects with the private runtime record."""++ node = self.execution_graph.get_node(execution_ref.exec_node_id)+ for effect in effects:+ if self._value_from_object(effect, "kind", "effect_type", "type") != "continuation":+ continue++ operation = self._value_from_object(effect, "operation")+ payload = self._normalize_continuation_payload(self._value_from_object(effect, "payload"))+ if isinstance(node, ForInvocation) and operation == "start":+ expected_payload = self._prepared_for_continuation_payload(node)+ if self._continuation_payload_key(payload) != self._continuation_payload_key(expected_payload):+ raise ValueError("continuation start payload does not match prepared For")+ continuation = self._for_continuation(execution_ref.exec_node_id)+ if payload is not None:+ if continuation.payload is not None and self._continuation_payload_key(+ continuation.payload+ ) != self._continuation_payload_key(payload):+ raise ValueError("started continuation has conflicting payload")+ if continuation.payload is None:+ 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):+ 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:+ continue+ continuation = self._for_continuation(for_exec_node_id)+ if continuation.terminal:+ if continuation.status == "completed" and self._continuation_payload_key(+ continuation.result+ ) != self._continuation_payload_key(payload):+ raise ValueError("completed continuation has conflicting result")+ continue+ previous = ContinuationRecord[Any].model_validate(continuation.model_dump(mode="python"))+ self._tx_record_once(+ ("continuation-complete", continuation.continuation_id),+ lambda previous=previous: self._generic_runtime().replace_continuation(previous),+ )+ continuation.complete(copydeep(payload))++ @staticmethod+ def _normalize_continuation_payload(payload: Any) -> Any:+ try:+ return _JSON_SERIALIZER.dump_python(payload, mode="json", warnings="error")+ except (PydanticSerializationError, TypeError, ValueError) as exc:+ raise ValueError("Continuation effect payload must be JSON-serializable") from exc++ @classmethod+ def _continuation_payload_key(cls, payload: Any) -> str:+ normalized = cls._normalize_continuation_payload(payload)+ return json.dumps(normalized, sort_keys=True, separators=(",", ":"), ensure_ascii=True)++ @classmethod+ def _for_start_continuation_payload(+ cls, node: ForInvocation, output: ForInvocationOutput | None = None+ ) -> dict[str, Any]:+ index = output.index if output is not None else node.index+ total = output.total if output is not None else len(node.collection)+ state = (output.state if output is not None else node.state) or LoopState()+ return {+ "index": index,+ "total": total,+ "state": cls._normalize_continuation_payload(state.model_dump(mode="json")),+ }++ @classmethod+ def _for_return_continuation_payload(+ cls, node: ForReturnInvocation, output: ForReturnInvocationOutput | None = None+ ) -> dict[str, Any] | None:+ if output is not None:+ output_value = output.output+ state = output.state+ else:+ output_value = node.output+ state = node.state+ return {+ "output": cls._normalize_continuation_payload(output_value),+ "state": cls._normalize_continuation_payload(state.model_dump(mode="json")) if state is not None else None,+ "continue_condition": node.continue_condition,+ }++ def _for_collection_for_validation(self, node: ForInvocation) -> list[Any]:+ if node.collection:+ return node.collection++ source_node_id = self.prepared_source_mapping.get(node.id)+ if source_node_id is None:+ return node.collection+ source_node = self.graph.get_node(source_node_id)+ if isinstance(source_node, ForInvocation) and source_node.collection:+ return source_node.collection++ collection_edges = self.graph._get_input_edges(source_node_id, COLLECTION_FIELD)+ if collection_edges:+ source_output = self.results.get(collection_edges[0].source.node_id)+ if source_output is None:+ parent_iteration_path = self._get_for_parent_iteration_path(node.id)+ source_output_ids = [+ exec_node_id+ for exec_node_id in self.source_prepared_mapping.get(collection_edges[0].source.node_id, ())+ if exec_node_id in self.results+ ]+ source_output = next(+ (+ self.results[exec_node_id]+ for exec_node_id in source_output_ids+ if self._get_iteration_path(exec_node_id) == parent_iteration_path+ ),+ None,+ )+ collection = self._value_from_object(source_output, collection_edges[0].source.field)+ if isinstance(collection, list):+ return collection+ return node.collection++ def _prepared_for_continuation_payload(self, node: ForInvocation | ForReturnInvocation) -> dict[str, Any] | None:+ if isinstance(node, ForInvocation):+ collection = self._for_collection_for_validation(node)+ state = node.state or LoopState()+ return {+ "index": node.index,+ "total": len(collection),+ "state": self._normalize_continuation_payload(state.model_dump(mode="json")),+ }+ return self._for_return_continuation_payload(node)++ def _for_item_for_validation(self, node: ForInvocation) -> Any:+ if node.index < 0:+ return None+ collection = self._for_collection_for_validation(node)+ if node.index >= len(collection):+ raise ValueError("For output item does not match prepared For")+ return collection[node.index]++ def _validate_for_continuation_output(+ self, execution_ref: ExecutionReference, output: BaseInvocationOutput+ ) -> None:+ node = self.execution_graph.get_node(execution_ref.exec_node_id)+ if isinstance(node, ForInvocation) and isinstance(output, ForInvocationOutput):+ expected_payload = self._prepared_for_continuation_payload(node)+ 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)+ ):+ 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)+ final_for_id = None+ if source_node_id is not None:+ final_candidates = [+ prepared_for_id+ for prepared_for_id in self.source_prepared_mapping.get(source_node_id, ())+ if self._get_for_parent_iteration_path(prepared_for_id) == parent_iteration_path+ ]+ if final_candidates:+ final_for_id = max(+ final_candidates,+ key=lambda prepared_for_id: self.execution_graph.get_node(prepared_for_id).index,+ )+ if (+ source_node_id is not None+ and final_for_id == node.id+ and self._is_loop_context_finalized(source_node_id, parent_iteration_path)+ ):+ body_path_to_return = self.graph._get_for_body_path_to_return(+ source_node_id, self._get_source_graph_flat()+ )+ if body_path_to_return is not None:+ _body_path_nodes, source_return_id = body_path_to_return+ return_outputs = self._get_ordered_for_return_outputs(node.id, source_return_id)+ expected_collection = [return_output.output for return_output in return_outputs]+ if self._continuation_payload_key(output.output_collection) != self._continuation_payload_key(+ expected_collection+ ):+ raise ValueError("For output output_collection is not authoritative")+ final_return = return_outputs[-1] if return_outputs else None+ expected_final_state = (+ self._get_loop_state_for_next_iteration(node.id, final_return)+ if final_return is not None+ else node.state+ )+ if self._continuation_payload_key(output.final_state) != self._continuation_payload_key(+ expected_final_state+ ):+ raise ValueError("For output final_state is not authoritative")++ 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):+ raise ValueError("ForReturn output does not match prepared ForReturn")++ def _requires_continuation_effect(self, execution_ref: ExecutionReference) -> bool:+ node = self.execution_graph.get_node(execution_ref.exec_node_id)+ if isinstance(node, ForReturnInvocation):+ return True+ if not isinstance(node, ForInvocation):+ return False+ output = self.results.get(execution_ref.exec_node_id)+ return isinstance(output, ForInvocationOutput) and output.total > 0+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)if continuation.terminal:+ if continuation.status == "completed" and self._continuation_payload_key(+ continuation.result+ ) != self._continuation_payload_key(result):+ raise ValueError("completed continuation has conflicting result")returnprevious = ContinuationRecord[Any].model_validate(continuation.model_dump(mode="python"))self._tx_record_once(("continuation-complete", continuation.continuation_id),lambda: self._generic_runtime().replace_continuation(previous),)- continuation.complete(result)+ continuation.complete(copydeep(result))def _register_generic_child_dependency(self) -> ChildDependencyRecord | None:execution = self.waiting_workflow_call_execution@@ -5398,14 +5617,22 @@ class GraphExecutionState(BaseModel):return wrapperdef _validate_effects(- self, execution_ref: ExecutionReference, effects: list[Any], effect_count: Optional[int]- ) -> None:+ self,+ execution_ref: ExecutionReference,+ effects: list[Any],+ effect_count: Optional[int],+ *,+ require_continuation: bool = False,+ ) -> list[Any]:expected_count = effect_count if effect_count is not None else execution_ref.effect_countif expected_count is not None and len(effects) != expected_count:raise ValueError(f"Effect count mismatch: expected {expected_count}, got {len(effects)}")node = self.execution_graph.get_node(execution_ref.exec_node_id)output_fields = type(node).get_output_annotation().model_fields+ continuation_payloads: dict[tuple[str, str], str] = {}+ duplicate_continuations: set[tuple[str, str]] = set()+ continuation_operations: set[str] = set()for effect in effects:try:_JSON_SERIALIZER.dump_python(effect, mode="json", warnings="error")@@ -5442,6 +5669,7 @@ class GraphExecutionState(BaseModel):raise ValueError(f"{type(node).__name__} continuation effect must use operation '{expected_operation}'")+ continuation_operations.add(operation)continuation_owner = self._value_from_object(effect,"execution_ref",@@ -5476,6 +5704,17 @@ class GraphExecutionState(BaseModel):execution_ref,"Continuation effect",)+ continuation_key = (operation, continuation_kind)+ continuation_payload = self._value_from_object(effect, "payload")+ serialized_payload = self._continuation_payload_key(continuation_payload)+ if continuation_key in continuation_payloads:+ if continuation_payloads[continuation_key] != serialized_payload:+ if operation == "complete":+ raise ValueError("completed continuation has conflicting result")+ raise ValueError("started continuation has conflicting payload")+ duplicate_continuations.add(continuation_key)+ else:+ continuation_payloads[continuation_key] = serialized_payloadowner = self._value_from_object(effect,@@ -5590,6 +5829,28 @@ class GraphExecutionState(BaseModel):):raise ValueError("Execution effect ports do not match prepared graph edge")+ if require_continuation and isinstance(node, ForInvocation) and "start" not in continuation_operations:+ raise ValueError("For execution must include a continuation effect")+ if require_continuation and isinstance(node, ForReturnInvocation) and "complete" not in continuation_operations:+ raise ValueError("ForReturn execution must include a continuation effect")++ if not duplicate_continuations:+ return effects++ seen_continuations: set[tuple[str, str]] = set()+ unique_effects: list[Any] = []+ for effect in effects:+ if self._value_from_object(effect, "kind", "effect_type", "type") == "continuation":+ continuation_key = (+ self._value_from_object(effect, "operation"),+ self._value_from_object(effect, "continuation_kind"),+ )+ if continuation_key in seen_continuations:+ continue+ seen_continuations.add(continuation_key)+ unique_effects.append(effect)+ return unique_effects+def _build_execution_tokens(self, execution_ref: ExecutionReference, output: BaseInvocationOutput, effects: Iterable[Any] = ()) -> dict[str, ExecutionToken]:@@ -5667,19 +5928,30 @@ class GraphExecutionState(BaseModel):ref = self._validate_execution_ref(execution_ref)if ref.exec_node_id in self.executed or ref.reference_id in self.execution_effects:raise ValueError(f"Execution reference {ref.reference_id} has already been applied")- result_effects = self._value_from_object(output, "effects", "effect_batch")- result_output = self._value_from_object(output, "output", "invocation_output", "result")- if result_output is not None:- output = result_output- if effects is None:- effects = result_effects+ if isinstance(output, BaseInvocationOutput):+ result_effects = None+ result_output = None+ else:+ result_effects = self._value_from_object(output, "effects", "effect_batch")+ result_output = self._value_from_object(output, "output", "invocation_output", "result")+ if result_output is not None:+ output = result_output+ if effects is None:+ effects = result_effectsoutput_value = self._validate_output_owner(ref, output)+ self._validate_for_continuation_output(ref, output_value)+ require_continuation = effects is not None or effect_count is not Noneif effects is None:effect_values = []else:batch_values = self._value_from_object(effects, "effects")effect_values = list(batch_values if batch_values is not None else effects)- self._validate_effects(ref, effect_values, effect_count)+ effect_values = self._validate_effects(+ ref,+ effect_values,+ effect_count,+ require_continuation=require_continuation,+ )tokens = self._build_execution_tokens(ref, output_value, effect_values)persisted_effects = copydeep(effect_values)@@ -5689,9 +5961,12 @@ class GraphExecutionState(BaseModel):transaction = _ApplyTransaction()object.__setattr__(self, "_apply_transaction", transaction)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)finalized_outputs = self.complete(ref.exec_node_id, output_value)self._record_effect_streams(ref, effect_values)- ref.effect_count = effect_count if effect_count is not None else ref.effect_count+ ref.effect_count = len(effect_values)self._tx_set_mapping(self.execution_refs, ref.exec_node_id, ref)for token_id, token in tokens.items():self._tx_set_mapping(self.execution_tokens, token_id, token)@@ -6041,14 +6316,51 @@ class GraphExecutionState(BaseModel):):self._record_empty_iterate_stream(source_node_id)- for reference_id, effects in self.execution_effects.items():- execution_ref = next(- (ref for ref in self.execution_refs.values() if ref.reference_id == reference_id),- None,- )- if execution_ref is not None:- self._validate_effects(execution_ref, list(effects), None)+ if not self._execution_effects_persisted and not self._legacy_execution_snapshot:+ raise ValueError("Execution effects ledger is missing from the current execution snapshot")++ if self._execution_effects_persisted:+ references_by_id = {ref.reference_id: ref for ref in self.execution_refs.values()}+ for reference_id, effects in self.execution_effects.items():+ execution_ref = references_by_id.get(reference_id)+ if execution_ref is None:+ raise ValueError("Execution effects contain an unknown execution reference")+ if execution_ref.exec_node_id not in self.results:+ raise ValueError("Execution effects belong to a pending execution node")+ if execution_ref.exec_node_id not in self.executed:+ raise ValueError("Execution effects require an executed marker")+ node = self.execution_graph.get_node(execution_ref.exec_node_id)+ effects = self._validate_effects(+ execution_ref,+ list(effects),+ len(effects),+ require_continuation=self._requires_continuation_effect(execution_ref),+ )+ self._record_continuation_effects(execution_ref, effects)self._record_effect_streams(execution_ref, effects)+ elif self._legacy_execution_snapshot:+ for reference_id, effects in self.execution_effects.items():+ execution_ref = next(+ (ref for ref in self.execution_refs.values() if ref.reference_id == reference_id),+ None,+ )+ if execution_ref is not None:+ effects = self._validate_effects(execution_ref, list(effects), None)+ self._record_continuation_effects(execution_ref, effects)+ self._record_effect_streams(execution_ref, effects)++ for exec_node_id, output in self.results.items():+ execution_ref = self.execution_refs.get(exec_node_id)+ if execution_ref is None:+ continue+ node = self.execution_graph.get_node(exec_node_id)+ if self._execution_effects_persisted and self._requires_continuation_effect(execution_ref):+ if execution_ref.reference_id not in self.execution_effects:+ raise ValueError(f"{type(node).__name__} execution must include a continuation effect")+ effects = self.execution_effects[execution_ref.reference_id]+ self._validate_effects(execution_ref, list(effects), len(effects), require_continuation=True)+ if self._execution_effects_persisted:+ self._validate_for_continuation_output(execution_ref, output)iterate_results: list[tuple[str, IterateInvocationOutput]] = []for exec_node_id, output in self.results.items():@@ -6065,7 +6377,8 @@ class GraphExecutionState(BaseModel):if source_node_id is not None and self._is_loop_context_finalized(source_node_id, self._get_for_parent_iteration_path(exec_node_id)):- continuation.complete(self.results[exec_node_id].model_dump(mode="json"))+ if not continuation.terminal:+ continuation.complete(self.results[exec_node_id].model_dump(mode="json"))self._register_generic_child_dependency()@@ -6089,6 +6402,9 @@ class GraphExecutionState(BaseModel):self._rehydrate_ready_queues()def model_post_init(self, __context: Any) -> None:+ 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._rehydrate_execution_refs()self._rehydrate_runtime_state()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.pyindex ca1b868a77..83a045d548 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@@ -21,7 +21,15 @@ from invokeai.app.services.session_processor.session_processor_default import ()from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueuefrom invokeai.app.services.shared.execution_effects import ExecutionEffectsRecorder, ExecutionInterface-from invokeai.app.services.shared.graph import CollectInvocation, Graph, GraphExecutionState, IterateInvocation+from invokeai.app.services.shared.execution_state_migration import dump_execution_state+from invokeai.app.services.shared.graph import (+ CollectInvocation,+ Graph,+ GraphExecutionState,+ IterateInvocation,+ _ExecutionScheduler,+ _GenericGraphSchedulerAdapter,+)from invokeai.app.services.shared.invocation_context import InvocationContextfrom tests.test_nodes import create_edge, create_loop_linkage@@ -97,6 +105,19 @@ def _build_iterate_collect_graph() -> Graph:return graph+def _build_flat_for_graph() -> Graph:+ graph = Graph()+ graph.add_node(ForInvocation(id="for", collection=[0, 1, 2]))+ graph.add_node(ForSqliteBodyInvocation(id="body"))+ graph.add_node(ForReturnInvocation(id="return"))+ graph.add_node(ForSqliteAfterInvocation(id="after"))+ graph.add_edge(create_edge("for", "item", "body", "value"))+ graph.add_edge(create_edge("body", "value", "return", "output"))+ graph.add_edge(create_edge("for", "output_collection", "after", "collection"))+ graph.add_edge(create_loop_linkage("for", "return"))+ return graph++def _build_nested_for_graph(*, fail_on: int | None = None) -> Graph:graph = Graph()graph.add_node(ForInvocation(id="outer_for", collection=[[1, 2], [3, 4]]))@@ -506,3 +527,104 @@ def test_processor_sqlite_iterate_collect_cancel_retry_does_not_leak_stream_statassert completed_streams[0].stream_id != canceled_stream_idassert completed_streams[0].stream_id.startswith(f"{completed_item.session.id}:iterate:")assert sum(len(effects) for effects in completed_item.session.execution_effects.values()) == 4++[email protected]("force_compatibility_scheduler", [False, True])+def test_processor_sqlite_flat_for_cancel_retry_isolates_execution_state(+ monkeypatch: pytest.MonkeyPatch,+ mock_invoker: Invoker,+ registered_event_bus: _RecordingRegisteredEventService,+ force_compatibility_scheduler: bool,+) -> None:+ monkeypatch.setattr(+ "invokeai.app.services.session_processor.session_processor_default.build_invocation_context",+ _build_test_invocation_context,+ )+ if force_compatibility_scheduler:+ monkeypatch.setattr(GraphExecutionState, "_can_use_generic_for_scheduler", lambda self: False)++ queue = SqliteSessionQueue(db=mock_invoker.services.board_records._db)+ mock_invoker.services.events = registered_event_bus+ mock_invoker.services.session_queue = queue+ mock_invoker.services.performance_statistics = _Stats()+ queue.start(mock_invoker)++ item_id = _insert_session(queue, _build_flat_for_graph())+ session_persisted = Event()+ completed_sources: list[str] = []++ def cancel_after_first_return(invocation, queue_item, output) -> None:+ source_id = queue_item.session.prepared_source_mapping[invocation.id]+ completed_sources.append(source_id)+ if source_id == "return":+ queue.cancel_queue_item(queue_item.item_id)++ processor = DefaultSessionProcessor(+ session_runner=DefaultSessionRunner(+ on_after_run_node_callbacks=[cancel_after_first_return],+ on_after_run_session_callbacks=[lambda queue_item: session_persisted.set()],+ ),+ polling_interval=0,+ )+ try:+ processor.start(mock_invoker)+ assert registered_event_bus.wait_for_status(item_id, "canceled")+ assert session_persisted.wait(timeout=5)+ finally:+ _stop_processor(processor)++ canceled_item = queue.get_queue_item(item_id)+ assert canceled_item.status == "canceled"+ assert completed_sources == ["for", "body", "return"]+ assert not canceled_item.session.is_complete()+ assert "after" not in canceled_item.session.source_prepared_mapping+ assert not canceled_item.session.finalized_loop_contexts+ canceled_snapshot = dump_execution_state(canceled_item.session)+ if force_compatibility_scheduler:+ assert isinstance(canceled_item.session._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(canceled_item.session._execution_scheduler, _GenericGraphSchedulerAdapter)++ retry_result = queue.retry_items_by_id("default", [item_id])+ assert retry_result.retried_item_ids == [item_id]+ [retried_item] = [+ queue_item for queue_item in queue.list_all_queue_items("default") if queue_item.retried_from_item_id == item_id+ ]+ assert retried_item.status == "pending"+ assert retried_item.item_id != item_id+ assert retried_item.session.id != canceled_item.session.id+ assert retried_item.session.results == {}+ assert retried_item.session.execution_refs == {}+ assert retried_item.session.execution_tokens == {}+ assert retried_item.session.execution_effects == {}+ retry_runtime = retried_item.session._generic_runtime()+ assert not retry_runtime.gates+ assert not retry_runtime.streams+ assert not retry_runtime.continuations++ retry_session_persisted = Event()+ retry_processor = DefaultSessionProcessor(+ session_runner=DefaultSessionRunner(+ on_after_run_session_callbacks=[lambda queue_item: retry_session_persisted.set()],+ ),+ polling_interval=0,+ )+ try:+ retry_processor.start(mock_invoker)+ assert registered_event_bus.wait_for_status(retried_item.item_id, "completed")+ assert retry_session_persisted.wait(timeout=5)+ finally:+ _stop_processor(retry_processor)++ canceled_item = queue.get_queue_item(item_id)+ completed_item = queue.get_queue_item(retried_item.item_id)+ assert canceled_item.status == "canceled"+ assert dump_execution_state(canceled_item.session) == canceled_snapshot+ assert completed_item.status == "completed"+ assert completed_item.session.id != canceled_item.session.id+ assert completed_item.session.is_complete()+ [after_execution_id] = completed_item.session.source_prepared_mapping["after"]+ assert completed_item.session.results[after_execution_id].collection == [0, 1, 2]+ assert all(+ reference.state_id == completed_item.session.id for reference in completed_item.session.execution_refs.values()+ )diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.pyindex c222b7b197..24268698bc 100644--- a/tests/app/services/shared/test_execution_effects.py+++ b/tests/app/services/shared/test_execution_effects.py@@ -1,3 +1,4 @@+from copy import deepcopyfrom typing import ClassVarfrom unittest.mock import MagicMock@@ -12,7 +13,13 @@ from invokeai.app.invocations.baseinvocation import ()from invokeai.app.invocations.fields import InputField, OutputFieldfrom invokeai.app.invocations.logic import IfInvocation, IfInvocationOutput-from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation, LoopState+from invokeai.app.invocations.loops import (+ ForInvocation,+ ForInvocationOutput,+ ForReturnInvocation,+ ForReturnInvocationOutput,+ LoopState,+)from invokeai.app.services.shared.execution_effects import (AddEdgeEffect,AwaitEffect,@@ -25,6 +32,7 @@ from invokeai.app.services.shared.execution_effects import (ExecutionRef,ExecutionToken,FailEffect,+ InvocationRunResult,RemoveEdgeEffect,SetValueEffect,SpawnExecutionEffect,@@ -290,6 +298,478 @@ def test_graph_state_accepts_for_continuation_effects_without_linkage_tokens() -assert dump_execution_state(restored)["execution_effects"] == snapshot["execution_effects"]+def _apply_flat_for_pair(+ collection: list[object], *, apply_return: bool = True+) -> tuple[GraphExecutionState, object, object]:+ graph = Graph()+ graph.add_node(ForInvocation(id="for", collection=collection))+ 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 isinstance(return_invocation, ForReturnInvocation)+ 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())+ if apply_return:+ state.apply(+ state.get_execution_ref(return_invocation.id, effect_count=len(return_result.effects)), return_result+ )+ return state, return_ref, return_result+++def test_graph_state_normalizes_for_continuation_result_before_rehydration() -> None:+ state, _return_ref, _return_result = _apply_flat_for_pair([("tuple",)])+ continuation = next(iter(state._generic_runtime().continuations.values()))+ expected_result = {"output": ["tuple"], "state": None, "continue_condition": True}++ assert continuation.result == expected_result+ restored = load_execution_state(dump_execution_state(state))+ restored_continuation = next(iter(restored._generic_runtime().continuations.values()))+ assert restored_continuation.result == expected_result+++def test_graph_state_rejects_type_distinct_for_continuation_replay() -> None:+ state, return_ref, return_result = _apply_flat_for_pair([1], apply_return=False)+ continuation_effect = return_result.effects[0]+ assert isinstance(continuation_effect, ContinuationEffect)+ replay_effect = continuation_effect.model_copy(+ deep=True,+ update={"payload": {**continuation_effect.payload, "output": True}},+ )+ before = dump_execution_state(state)++ with pytest.raises(ValueError, match="completed continuation has conflicting result"):+ state.apply(return_ref, return_result, [continuation_effect, replay_effect], effect_count=2)++ assert dump_execution_state(state) == before+++def test_graph_state_rejects_malformed_for_start_payload_transactionally() -> 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)+ context = _context()+ 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,+ )+ context.execution = ExecutionInterface(context.execution_effects)+ result = for_invocation.invoke_internal_with_effects(context, _services())+ effect = result.effects[0]+ assert isinstance(effect, ContinuationEffect)+ malformed = effect.model_copy(deep=True, update={"payload": {**effect.payload, "index": 1}})+ before = dump_execution_state(state)++ with pytest.raises(ValueError, match="continuation start payload"):+ state.apply(for_ref, result, [malformed], effect_count=1)++ assert dump_execution_state(state) == before+++def test_graph_state_rejects_forged_for_output_with_matching_start_effect() -> 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)+ context = _context()+ context.execution_effects = ExecutionEffectsRecorder(+ source_node_id=invocation.id,+ frame_path=execution_ref.frame.iteration_path,+ state_id=execution_ref.state_id,+ frame_id=execution_ref.frame.frame_id,+ workflow_call_depth=execution_ref.frame.workflow_call_depth,+ )+ context.execution = ExecutionInterface(context.execution_effects)+ result = invocation.invoke_internal_with_effects(context, _services())+ effect = result.effects[0]+ assert isinstance(effect, ContinuationEffect)+ forged_state = LoopState(values={"forged": True})+ forged_output = result.output.model_copy(update={"index": 99, "total": 99, "state": forged_state})+ assert isinstance(forged_output, ForInvocationOutput)+ forged_effect = effect.model_copy(+ deep=True,+ update={+ "payload": {+ "index": 99,+ "total": 99,+ "state": forged_state.model_dump(mode="json"),+ }+ },+ )+ before = dump_execution_state(state)++ with pytest.raises(ValueError, match="For output does not match prepared For"):+ state.apply(+ execution_ref,+ InvocationRunResult(output=forged_output, effects=result.effects),+ [forged_effect],+ effect_count=1,+ )++ assert dump_execution_state(state) == before+++def test_graph_state_rejects_forged_for_return_output_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 = ForReturnInvocationOutput(output="forged", state=forged_state)+ forged_effect = effect.model_copy(+ deep=True,+ update={+ "payload": {+ "output": "forged",+ "state": forged_state.model_dump(mode="json"),+ "continue_condition": True,+ }+ },+ )+ 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"]))+ 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)+ context = _context()+ context.execution_effects = ExecutionEffectsRecorder(+ source_node_id=invocation.id,+ frame_path=execution_ref.frame.iteration_path,+ state_id=execution_ref.state_id,+ frame_id=execution_ref.frame.frame_id,+ workflow_call_depth=execution_ref.frame.workflow_call_depth,+ )+ context.execution = ExecutionInterface(context.execution_effects)+ result = invocation.invoke_internal_with_effects(context, _services())+ forged_output = result.output.model_copy(update={"item": "forged"})+ before = dump_execution_state(state)++ with pytest.raises(ValueError, match="For output item does not match"):+ state.apply(+ execution_ref,+ InvocationRunResult(output=forged_output, effects=result.effects),+ result.effects,+ effect_count=len(result.effects),+ )++ assert dump_execution_state(state) == before+++def test_graph_state_rejects_persisted_for_result_tampering() -> None:+ state, _return_ref, _return_result = _apply_flat_for_pair(["item"])+ for_exec_id = next(+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "for"+ )+ start_ref = state.get_execution_ref(for_exec_id)+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["results"][for_exec_id]["index"] = 99+ snapshot["results"][for_exec_id]["total"] = 99+ snapshot["results"][for_exec_id]["state"] = {"values": {"forged": True}}+ start_effect = snapshot["execution_effects"][start_ref.reference_id][0]+ start_effect["payload"] = {+ "index": 99,+ "total": 99,+ "state": {"values": {"forged": True}},+ }++ with pytest.raises(ValueError, match="continuation start payload"):+ load_execution_state(snapshot)+++def test_graph_state_rejects_persisted_for_result_only_tampering_with_valid_effect() -> None:+ state, _return_ref, _return_result = _apply_flat_for_pair(["item"])+ for_exec_id = next(+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "for"+ )+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["results"][for_exec_id]["item"] = "forged"++ with pytest.raises(ValueError, match="For output item does not match prepared For"):+ load_execution_state(snapshot)+++def test_graph_state_rejects_effect_for_pending_for_return() -> None:+ state, return_ref, return_result = _apply_flat_for_pair(["item"], apply_return=False)+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["execution_effects"][return_ref.reference_id] = [return_result.effects[0].model_dump(mode="json")]++ with pytest.raises(ValueError, match="pending execution node"):+ load_execution_state(snapshot)+++def test_graph_state_rejects_for_effect_in_wrong_persisted_bucket() -> None:+ state, return_ref, _return_result = _apply_flat_for_pair(["item"], apply_return=False)+ for_exec_id = next(+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "for"+ )+ for_ref = state.get_execution_ref(for_exec_id)+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["execution_effects"][return_ref.reference_id] = snapshot["execution_effects"].pop(for_ref.reference_id)++ with pytest.raises(ValueError, match="pending execution node"):+ load_execution_state(snapshot)+++def test_graph_state_rejects_nested_execution_owner_tampering() -> None:+ state, return_ref, _return_result = _apply_flat_for_pair(["item"], apply_return=False)+ for_exec_id = next(+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "for"+ )+ for_ref = state.get_execution_ref(for_exec_id)+ snapshot = deepcopy(dump_execution_state(state))+ effect = snapshot["execution_effects"][for_ref.reference_id][0]+ effect["execution_ref"]["execution_node_id"] = return_ref.exec_node_id++ with pytest.raises(ValueError, match="Execution effect is not owned by execution reference"):+ load_execution_state(snapshot)+++def test_graph_state_rejects_missing_for_start_effect_transactionally() -> 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)+ context = _context()+ context.execution_effects = ExecutionEffectsRecorder(+ source_node_id=invocation.id,+ frame_path=execution_ref.frame.iteration_path,+ state_id=execution_ref.state_id,+ frame_id=execution_ref.frame.frame_id,+ workflow_call_depth=execution_ref.frame.workflow_call_depth,+ )+ context.execution = ExecutionInterface(context.execution_effects)+ result = invocation.invoke_internal_with_effects(context, _services())+ before = dump_execution_state(state)++ with pytest.raises(ValueError, match="must include a continuation effect"):+ state.apply(execution_ref, result, [], effect_count=0)++ assert dump_execution_state(state) == before+++def test_graph_state_requires_for_return_continuation_effect() -> None:+ state, return_ref, return_result = _apply_flat_for_pair(["item"], apply_return=False)++ with pytest.raises(ValueError, match="must include a continuation effect"):+ state.apply(return_ref, return_result, [], effect_count=0)+++def test_graph_state_applies_direct_for_return_output() -> None:+ state, return_ref, return_result = _apply_flat_for_pair(["item"], apply_return=False)++ state.apply(return_ref, return_result)++ assert state.is_complete()+++def test_graph_state_applies_direct_for_return_output_with_effects() -> None:+ state, return_ref, return_result = _apply_flat_for_pair(["item"], apply_return=False)++ state.apply(+ return_ref,+ return_result.output,+ return_result.effects,+ effect_count=len(return_result.effects),+ )++ assert state.is_complete()++[email protected]("conflicting", [False, True], ids=["exact-replay", "conflicting-payload"])+def test_graph_state_reconciles_duplicate_flat_for_continuation_effects(conflicting: bool) -> 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 isinstance(return_invocation, ForReturnInvocation)+ 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())+ continuation_effect = return_result.effects[0]+ assert isinstance(continuation_effect, ContinuationEffect)+ replay_effect = continuation_effect+ if conflicting:+ replay_effect = continuation_effect.model_copy(+ deep=True,+ update={"payload": {**continuation_effect.payload, "output": "conflict"}},+ )++ before = dump_execution_state(state)+ if conflicting:+ with pytest.raises(ValueError, match="completed continuation has conflicting result"):+ state.apply(+ return_ref,+ return_result,+ [continuation_effect, replay_effect],+ effect_count=2,+ )+ assert dump_execution_state(state) == before+ else:+ state.apply(+ return_ref,+ return_result,+ [continuation_effect, replay_effect],+ effect_count=2,+ )+ assert len(state._generic_runtime().continuations) == 1+ assert state.execution_effects[return_ref.reference_id] == [continuation_effect]++@pytest.mark.parametrize(("owner_kwargs", "message"),[diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex a585ff793a..b1b1cc04dd 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 annotationsimport jsonfrom pathlib import Pathfrom typing import Any-from unittest.mock import Mock+from unittest.mock import Mock, patchimport pytestfrom pydantic import ValidationError@@ -28,7 +28,8 @@ from invokeai.app.services.shared.graph import (_GenericGraphSchedulerAdapter,_IfBranchScheduler,)-from tests.test_nodes import AnyTypeTestInvocation+from invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_context+from tests.test_nodes import AnyTypeTestInvocation, ErrorInvocation, UnionCollectionTestInvocationFIXTURE_PATH = Path(__file__).parents[3] / "fixtures" / "execution_engine" / "static_dag_v1.json"@@ -100,17 +101,33 @@ def _nested_if_graph() -> Graph:return graph-def _flat_for_graph(*, with_after: bool = False) -> Graph:+def _flat_for_graph(+ *,+ with_after: bool = False,+ collection: list[Any] | None = None,+ input_collection: list[Any] | None = None,+ body_returns_none: bool = False,+) -> Graph:graph = Graph()- graph.add_node(ForInvocation(id="for", collection=[1, 2]))- graph.add_node(AddInvocation(id="body", b=10))+ collection = [1, 2] if collection is None else collection+ graph.add_node(ForInvocation(id="for", collection=collection))+ if input_collection is not None:+ graph.add_node(AnyTypeTestInvocation(id="collection", value=input_collection))+ graph.add_node(UnionCollectionTestInvocation(id="body") if body_returns_none else AddInvocation(id="body", b=10))graph.add_node(ForReturnInvocation(id="return"))if with_after:graph.add_node(AnyTypeTestInvocation(id="after"))+ if input_collection is not None:+ graph.add_edge(+ Edge(+ source=EdgeConnection(node_id="collection", field="value"),+ destination=EdgeConnection(node_id="for", field="collection"),+ )+ )graph.add_edge(Edge(source=EdgeConnection(node_id="for", field="item"),- destination=EdgeConnection(node_id="body", field="a"),+ destination=EdgeConnection(node_id="body", field="value" if body_returns_none else "a"),))graph.add_edge(@@ -199,6 +216,59 @@ def _run_graph(return trace, state+def _run_graph_with_effects(+ state: GraphExecutionState,+ *,+ force_compatibility_scheduler: bool = False,+ stop_after_source: str | None = None,+ fail_source_id: str | None = None,+ stop_after: int | None = None,+) -> tuple[list[str], GraphExecutionState]:+ """Run a graph through the same invocation/effect/apply path as the session runner."""+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)++ services = Mock()+ services.invocation_cache.get.return_value = None+ trace: list[str] = []+ while (node := state.next()) is not None:+ source_id = state.prepared_source_mapping[node.id]+ trace.append(source_id)+ execution_ref = state.get_execution_ref(node.id)+ context = build_invocation_context(+ services=services,+ data=InvocationContextData(+ queue_item=None, # type: ignore[arg-type]+ invocation=node,+ source_invocation_id=source_id,+ 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,+ ),+ is_canceled=lambda: False,+ )+ try:+ if source_id == fail_source_id:+ with patch.object(+ type(node),+ "invoke_internal_with_effects",+ side_effect=RuntimeError("injected failure"),+ ):+ run_result = node.invoke_internal_with_effects(context, services)+ else:+ run_result = node.invoke_internal_with_effects(context, services)+ except RuntimeError as exc:+ state.set_node_error(node.id, str(exc))+ break+ state.apply(state.get_execution_ref(node.id, effect_count=len(run_result.effects)), run_result)+ if stop_after_source == source_id:+ break+ if stop_after is not None and len(trace) == stop_after:+ break+ return trace, state++def _run_until_source(state: GraphExecutionState,source_id_to_stop: str,@@ -289,6 +359,32 @@ def _activation_projection(state: GraphExecutionState) -> tuple[tuple[str, str,def _execution_identity_projection(state: GraphExecutionState) -> tuple[Any, ...]:+ def json_projection(value: Any) -> str:+ if hasattr(value, "model_dump"):+ value = value.model_dump(mode="json")+ return json.dumps(value, sort_keys=True)++ def normalize_effect_identity(value: Any) -> Any:+ if hasattr(value, "model_dump"):+ value = value.model_dump(mode="json", warnings=False)+ if isinstance(value, dict):+ return {+ key: normalize_effect_identity(item)+ for key, item in value.items()+ if key+ not in {+ "state_id",+ "execution_node_id",+ "frame_id",+ "reference_id",+ "template_node_id",+ "token",+ }+ }+ if isinstance(value, list):+ return [normalize_effect_identity(item) for item in value]+ return value+references = tuple(sorted((@@ -307,7 +403,7 @@ def _execution_identity_projection(state: GraphExecutionState) -> tuple[Any, ...(state.prepared_source_mapping.get(token.owner_node_id, token.owner_node_id),token.port,- json.dumps(token.value, sort_keys=True),+ json_projection(token.value),token.token_kind,token.sequence,tuple(token.frame.iteration_path),@@ -331,10 +427,7 @@ def _execution_identity_projection(state: GraphExecutionState) -> tuple[Any, ...reference_id,),json.dumps(- [- effect.model_dump(mode="json", warnings=False) if hasattr(effect, "model_dump") else effect- for effect in effect_values- ],+ [normalize_effect_identity(effect) for effect in effect_values],sort_keys=True,),)@@ -344,6 +437,36 @@ def _execution_identity_projection(state: GraphExecutionState) -> tuple[Any, ...return references, tokens, effects+def _continuation_projection(state: GraphExecutionState) -> tuple[Any, ...]:+ return tuple(+ sorted(+ (+ state.prepared_source_mapping.get(continuation.owner_id, continuation.owner_id),+ continuation.kind,+ continuation.status,+ tuple(continuation.frame.iteration_path),+ continuation.frame.workflow_call_depth,+ json.dumps(continuation.payload, sort_keys=True),+ json.dumps(continuation.result, sort_keys=True),+ continuation.error,+ )+ for continuation in state._generic_runtime().continuations.values()+ )+ )+++def _final_for_output(state: GraphExecutionState) -> Any:+ final_for_id = max(+ (+ exec_node_id+ for exec_node_id, source_node_id in state.prepared_source_mapping.items()+ if source_node_id == "for"+ ),+ key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,+ )+ return state.results[final_for_id]++def _execution_edge_projection(state: GraphExecutionState) -> tuple[tuple[str, str, str, str, str], ...]:return tuple(sorted(@@ -359,6 +482,50 @@ def _execution_edge_projection(state: GraphExecutionState) -> tuple[tuple[str, s)+def _effect_ledger_projection(state: GraphExecutionState) -> tuple[Any, ...]:+ """Compare persisted effects while ignoring generated state/reference IDs."""++ def normalized(value: Any) -> Any:+ if hasattr(value, "model_dump"):+ value = value.model_dump(mode="json")+ if isinstance(value, dict):+ return tuple(+ sorted(+ (key, normalized(item))+ for key, item in value.items()+ if key+ not in {+ "state_id",+ "execution_node_id",+ "frame_id",+ "reference_id",+ "template_node_id",+ "token",+ }+ )+ )+ if isinstance(value, list):+ return tuple(normalized(item) for item in value)+ return value++ return tuple(+ sorted(+ (+ next(+ (+ state.prepared_source_mapping.get(exec_node_id, exec_node_id)+ for exec_node_id, reference in state.execution_refs.items()+ if reference.reference_id == reference_id+ ),+ reference_id,+ ),+ normalized(effects),+ )+ for reference_id, effects in state.execution_effects.items()+ )+ )++def _source_edge_projection(graph: Graph) -> tuple[tuple[str, str, str, str, str], ...]:return tuple(sorted(@@ -456,6 +623,18 @@ def _expected_remaining_input_indegree(def _assert_execution_identity_consistent(state: GraphExecutionState) -> None:+ def value_from_object(value: Any, *names: str) -> Any:+ if isinstance(value, dict):+ for name in names:+ if name in value:+ return value[name]+ return None+ for name in names:+ candidate = getattr(value, name, None)+ if candidate is not None:+ return candidate+ return None+for exec_node_id, reference in state.execution_refs.items():if exec_node_id not in state.prepared_source_mapping:continue@@ -480,6 +659,34 @@ def _assert_execution_identity_consistent(state: GraphExecutionState) -> None:assert token.port in activation_fieldsassert token.token_id == f"{expected.reference_id}:activation:{token.port}"assert token.value == token.port+ references_by_id = {reference.reference_id: reference for reference in state.execution_refs.values()}+ for reference_id, effects in state.execution_effects.items():+ reference = references_by_id[reference_id]+ for effect in effects:+ effect_reference = value_from_object(+ effect,+ "execution_ref",+ "execution_reference",+ "owner_ref",+ "owner",+ )+ assert effect_reference is not None+ assert value_from_object(effect_reference, "state_id", "session_id") == reference.state_id+ assert value_from_object(effect_reference, "execution_node_id", "node_id") == reference.exec_node_id+ assert value_from_object(effect_reference, "frame_id") == reference.frame.frame_id+ assert tuple(value_from_object(effect_reference, "frame_path", "iteration_path") or ()) == tuple(+ reference.frame.iteration_path+ )+ assert value_from_object(effect_reference, "workflow_call_depth", "call_depth", "depth") == (+ reference.frame.workflow_call_depth+ )+++def _assert_generic_and_compatibility_schedulers(+ generic_state: GraphExecutionState, compatibility_state: GraphExecutionState+) -> None:+ assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ assert isinstance(compatibility_state._execution_scheduler, _ExecutionScheduler)def test_static_dag_fresh_execution_has_matching_source_trace() -> None:@@ -555,6 +762,7 @@ def test_nested_if_fresh_execution_matches_compatibility_scheduler(== expected_value)assert _state_projection(generic_state) == _state_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)expected_activations = [("outer_if", "true_input" if outer_condition else "false_input"),]@@ -597,8 +805,8 @@ def test_nested_if_fresh_execution_matches_compatibility_scheduler(def test_flat_for_fresh_execution_matches_compatibility_scheduler() -> None:- generic_trace, generic_state = _run_graph(GraphExecutionState(graph=_flat_for_graph()))- compatibility_trace, compatibility_state = _run_graph(+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()))+ compatibility_trace, compatibility_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()),force_compatibility_scheduler=True,)@@ -607,7 +815,7 @@ def test_flat_for_fresh_execution_matches_compatibility_scheduler() -> None:assert _state_projection(generic_state) == _state_projection(compatibility_state)assert generic_state.is_complete()assert compatibility_state.is_complete()- assert isinstance(generic_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)final_for_id = max((exec_node_id@@ -631,10 +839,10 @@ def test_flat_for_fresh_execution_matches_compatibility_scheduler() -> None:def test_flat_for_fresh_execution_releases_after_loop_consumer() -> None:- generic_trace, generic_state = _run_graph(+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph(with_after=True)),)- compatibility_trace, compatibility_state = _run_graph(+ compatibility_trace, compatibility_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph(with_after=True)),force_compatibility_scheduler=True,)@@ -654,6 +862,304 @@ def test_flat_for_fresh_execution_releases_after_loop_consumer() -> None:)].value == [11, 12]assert _state_projection(generic_state) == _state_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)+++def test_flat_for_none_output_matches_compatibility_scheduler() -> None:+ graph = _flat_for_graph(collection=[None, None], body_returns_none=True)+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=graph.model_copy(deep=True)))+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return"]+ assert _final_for_output(generic_state).output_collection == [None, None]+ assert _final_for_output(compatibility_state).output_collection == [None, None]+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _execution_identity_projection(generic_state) == _execution_identity_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)+++def test_flat_for_apply_path_matches_compatibility_scheduler() -> None:+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph(with_after=True)))+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph(with_after=True)),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace == ["for", "body", "return", "for", "body", "return", "after"]+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _effect_ledger_projection(generic_state) == _effect_ledger_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)+ for state in (generic_state, compatibility_state):+ after_id = next(+ execution_id for execution_id, source_id in state.prepared_source_mapping.items() if source_id == "after"+ )+ assert state.results[after_id].value == [11, 12]+ assert _final_for_output(state).output_collection == [11, 12]++ continuations = sorted(+ state._generic_runtime().continuations.values(), key=lambda continuation: continuation.frame.iteration_path+ )+ assert [+ (+ state.prepared_source_mapping[continuation.owner_id],+ continuation.kind,+ continuation.status,+ tuple(continuation.frame.iteration_path),+ continuation.frame.state_id,+ continuation.frame.workflow_call_depth,+ )+ for continuation in continuations+ ] == [+ ("for", "for", "completed", (0,), state.id, 0),+ ("for", "for", "completed", (1,), state.id, 0),+ ]+ continuation_effects = sorted(+ (+ state.prepared_source_mapping[effect.execution_ref.node_id],+ effect.operation,+ effect.continuation_kind,+ tuple(effect.execution_ref.frame),+ )+ for effects in state.execution_effects.values()+ for effect in effects+ if effect.kind == "continuation"+ )+ assert continuation_effects == [+ ("for", "start", "for", (0,)),+ ("for", "start", "for", (1,)),+ ("return", "complete", "for", (0,)),+ ("return", "complete", "for", (1,)),+ ]+++def test_flat_for_apply_partial_rehydration_preserves_continuation_runtime() -> None:+ graph = _flat_for_graph(with_after=True, collection=[None, None], body_returns_none=True)+ resumed_projections: list[tuple[Any, ...]] = []++ for force_compatibility_scheduler in (False, True):+ expected_trace, expected_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ partial_trace, partial_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ force_compatibility_scheduler=force_compatibility_scheduler,+ stop_after_source="return",+ )+ restored = load_execution_state(dump_execution_state(partial_state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)++ assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)+ # Rehydration reconstructs references for all prepared nodes, while the partial in-memory+ # state only has references for nodes reached so far. Compare durable tokens/effects here;+ # resumed execution below compares the complete identity projection.+ assert _execution_identity_projection(restored)[1:] == _execution_identity_projection(partial_state)[1:]+ _assert_execution_identity_consistent(restored)+ assert any(+ (effect.get("kind") if isinstance(effect, dict) else effect.kind) == "continuation"+ and (effect.get("operation") if isinstance(effect, dict) else effect.operation) == "complete"+ and (effect.get("payload") if isinstance(effect, dict) else effect.payload)+ == {"output": None, "state": None, "continue_condition": True}+ for effects in restored.execution_effects.values()+ for effect in effects+ )++ remaining_trace, resumed_state = _run_graph_with_effects(+ restored,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )++ assert partial_trace + remaining_trace == expected_trace+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ assert _continuation_projection(resumed_state) == _continuation_projection(expected_state)+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)+ assert _execution_identity_projection(resumed_state) == _execution_identity_projection(expected_state)+ assert _final_for_output(resumed_state).output_collection == [None, None]+ _assert_execution_identity_consistent(resumed_state)+ if force_compatibility_scheduler:+ assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ resumed_projections.append(+ (+ _state_projection(resumed_state),+ _continuation_projection(resumed_state),+ _effect_ledger_projection(resumed_state),+ _execution_identity_projection(resumed_state),+ )+ )++ assert resumed_projections[0] == resumed_projections[1]+++ ("fail_source_id", "expected_trace"),+ [+ ("body", ["for", "body"]),+ ("return", ["for", "body", "return"]),+ ],+)+def test_flat_for_failure_matches_compatibility_scheduler(fail_source_id: str, expected_trace: list[str]) -> None:+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph()),+ fail_source_id=fail_source_id,+ )+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph()),+ force_compatibility_scheduler=True,+ fail_source_id=fail_source_id,+ )++ assert generic_trace == compatibility_trace == expected_trace+ for state in (generic_state, compatibility_state):+ assert state.next() is None+ assert {+ state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()+ } == {fail_source_id: "injected failure"}+ assert state.is_complete()+ assert sum(len(effects) for effects in state.execution_effects.values()) == 1+ assert all(item.status == "running" for item in state._generic_runtime().continuations.values())+ _assert_execution_identity_consistent(state)+ restored = load_execution_state(dump_execution_state(state))+ if isinstance(state._execution_scheduler, _ExecutionScheduler):+ _restore_compatibility_scheduler(restored)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)+ assert _continuation_projection(restored) == _continuation_projection(state)+ _assert_execution_identity_consistent(restored)+ assert {+ state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in restored.errors.items()+ } == {fail_source_id: "injected failure"}+ assert restored.next() is None+ assert restored.is_complete()+ if isinstance(state._execution_scheduler, _ExecutionScheduler):+ assert isinstance(restored._execution_scheduler, _ExecutionScheduler)+ else:+ assert restored._execution_scheduler is None+ assert _state_projection(generic_state) == _state_projection(compatibility_state)++[email protected]("stop_after_source", ["for", "body"])+def test_flat_for_partial_rehydration_matches_compatibility_scheduler(stop_after_source: str) -> None:+ graph = _flat_for_graph()+ expected_trace, expected_state = _run_graph_with_effects(GraphExecutionState(graph=graph.model_copy(deep=True)))+ resumed_projections: list[tuple[Any, ...]] = []++ for force_compatibility_scheduler in (False, True):+ partial_trace, partial_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph.model_copy(deep=True)),+ stop_after_source=stop_after_source,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )+ snapshot = dump_execution_state(partial_state)+ restored = load_execution_state(snapshot)+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)++ remaining_trace, resumed_state = _run_graph_with_effects(+ restored,+ force_compatibility_scheduler=force_compatibility_scheduler,+ )++ assert partial_trace + remaining_trace == expected_trace+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ # Rehydration reconstructs durable execution references for all prepared nodes; a fresh+ # in-memory run does not retain those references after terminal cleanup. Compare the+ # durable token/effect portions directly and compare references across the two resumed+ # scheduler paths below.+ assert _execution_identity_projection(resumed_state)[1:] == _execution_identity_projection(expected_state)[1:]+ assert _continuation_projection(resumed_state) == _continuation_projection(expected_state)+ _assert_execution_identity_consistent(resumed_state)+ if force_compatibility_scheduler:+ assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)+ else:+ assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)+ resumed_projections.append((_state_projection(resumed_state), _execution_identity_projection(resumed_state)))++ assert resumed_projections[0] == resumed_projections[1]+++def test_flat_for_frame_and_continuation_identity_matches_compatibility_scheduler() -> None:+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()), stop_after=4)+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=_flat_for_graph()),+ force_compatibility_scheduler=True,+ stop_after=4,+ )++ assert generic_trace == compatibility_trace == ["for", "body", "return", "for"]+ assert _execution_identity_projection(generic_state) == _execution_identity_projection(compatibility_state)+ assert _continuation_projection(generic_state) == _continuation_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)+ for state in (generic_state, compatibility_state):+ continuations = sorted(+ state._generic_runtime().continuations.values(), key=lambda item: item.frame.iteration_path+ )+ assert len(continuations) == 2+ assert [tuple(item.frame.iteration_path) for item in continuations] == [(0,), (1,)]+ assert {state.prepared_source_mapping[item.owner_id] for item in continuations} == {"for"}+ assert {item.frame.state_id for item in continuations} == {state.id}+ assert {item.frame.workflow_call_depth for item in continuations} == {0}+ frame_ids = [item.frame.frame_id for item in continuations]+ assert all(frame_ids)+ assert len(set(frame_ids)) == len(frame_ids)+ assert all(+ item.frame.model_dump(mode="json")+ == state._expected_execution_ref(item.owner_id).frame.model_dump(mode="json")+ for item in continuations+ )+ assert [item.status for item in continuations] == ["completed", "running"]+ _assert_execution_identity_consistent(state)++ generic_frames = {item.frame.frame_id for item in generic_state._generic_runtime().continuations.values()}+ compatibility_frames = {+ item.frame.frame_id for item in compatibility_state._generic_runtime().continuations.values()+ }+ assert generic_frames.isdisjoint(compatibility_frames)++ other_trace, other_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_graph()), stop_after=4)+ assert other_trace == generic_trace+ other_frames = {item.frame.frame_id for item in other_state._generic_runtime().continuations.values()}+ generic_frames = {item.frame.frame_id for item in generic_state._generic_runtime().continuations.values()}+ assert other_frames.isdisjoint(generic_frames)+++ ("graph_kwargs", "expected_trace", "expected_collection"),+ [+ ({"collection": []}, [], []),+ ({"input_collection": [1, 2]}, ["collection", "for", "body", "return", "for", "body", "return"], [11, 12]),+ ],+)+def test_flat_for_ineligible_collections_use_compatibility_scheduler(+ graph_kwargs: dict[str, list[Any]], expected_trace: list[str], expected_collection: list[Any]+) -> None:+ state = GraphExecutionState(graph=_flat_for_graph(**graph_kwargs))++ assert state._can_use_generic_scheduler() is False+ trace, state = _run_graph_with_effects(state)++ assert trace == expected_trace+ assert isinstance(state._execution_scheduler, _ExecutionScheduler)+ assert _final_for_output(state).output_collection == expected_collection+ assert state.is_complete()+ continuations = list(state._generic_runtime().continuations.values())+ assert len(continuations) == len(expected_collection)+ assert all(state.prepared_source_mapping[item.owner_id] == "for" for item in continuations)+ assert all(item.status == "completed" for item in continuations)+ assert sum(len(effects) for effects in state.execution_effects.values()) == 2 * len(expected_collection)+ _assert_execution_identity_consistent(state)++ restored = load_execution_state(dump_execution_state(state))+ _restore_compatibility_scheduler(restored)+ assert isinstance(restored._execution_scheduler, _ExecutionScheduler)+ assert _state_projection(restored) == _state_projection(state)+ assert _effect_ledger_projection(restored) == _effect_ledger_projection(state)+ assert _continuation_projection(restored) == _continuation_projection(state)+ _assert_execution_identity_consistent(restored)@pytest.mark.parametrize(@@ -669,10 +1175,10 @@ def test_flat_for_fresh_execution_matches_state_and_break_semantics(expected_collection: list[int],expected_state: dict[str, int],) -> None:- generic_trace, generic_state = _run_graph(+ generic_trace, generic_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_state_graph(continue_condition)),)- compatibility_trace, compatibility_state = _run_graph(+ compatibility_trace, compatibility_state = _run_graph_with_effects(GraphExecutionState(graph=_flat_for_state_graph(continue_condition)),force_compatibility_scheduler=True,)@@ -690,6 +1196,7 @@ def test_flat_for_fresh_execution_matches_state_and_break_semantics(assert final_for_output.output_collection == expected_collectionassert final_for_output.final_state == LoopState(values=expected_state)assert _state_projection(generic_state) == _state_projection(compatibility_state)+ _assert_generic_and_compatibility_schedulers(generic_state, compatibility_state)def test_nested_if_checkpoint_restore_matches_compatibility_scheduler() -> None:@@ -815,6 +1322,42 @@ def test_injected_failure_round_trip_preserves_both_scheduler_terminal_state() -assert _state_projection(restored_generic) == _state_projection(restored_compatibility)+def test_real_invocation_failure_round_trip_preserves_both_scheduler_terminal_state() -> None:+ expected_error = "This invocation is supposed to fail"+ terminal_states: list[tuple[str, bool, bool]] = []++ for force_compatibility_scheduler in (False, True):+ graph = Graph()+ graph.add_node(ErrorInvocation(id="error"))+ state = GraphExecutionState(graph=graph)+ if force_compatibility_scheduler:+ state._execution_scheduler = _ExecutionScheduler(state)++ node = state.next()+ assert node is not None+ with pytest.raises(Exception) as invocation_error:+ node.invoke(Mock())+ assert str(invocation_error.value) == expected_error+ state.set_node_error(node.id, str(invocation_error.value))++ assert state.next() is None+ assert state.is_complete()+ assert {+ state.prepared_source_mapping.get(node_id, node_id): message for node_id, message in state.errors.items()+ } == {"error": expected_error}++ restored = load_execution_state(dump_execution_state(state))+ if force_compatibility_scheduler:+ _restore_compatibility_scheduler(restored)++ assert restored.errors == state.errors+ assert restored.next() is None+ assert restored.is_complete()+ terminal_states.append((str(next(iter(restored.errors.values()))), True, restored.is_complete()))++ assert terminal_states == [(expected_error, True, True), (expected_error, True, True)]++@pytest.mark.parametrize("fixture_name", ["static_dag_partial_v1.json", "static_dag_failed_v1.json"])def test_durable_snapshot_corpus_round_trips_without_losing_terminal_state(fixture_name: str) -> None:state = _load_fixture(fixture_name)diff --git a/tests/app/services/shared/test_execution_engine_primitives.py b/tests/app/services/shared/test_execution_engine_primitives.pyindex e47c6a98bc..ed7977a917 100644--- a/tests/app/services/shared/test_execution_engine_primitives.py+++ b/tests/app/services/shared/test_execution_engine_primitives.py@@ -150,6 +150,40 @@ def test_continuation_record_has_atomic_idempotent_status_transitions() -> None:assert continuation.error is None+ ("terminal_method", "value", "conflicting_value", "error"),+ [+ ("complete", {"output": 2}, {"output": 3}, "completed continuation has conflicting result"),+ ("fail", "first failure", "different failure", "failed continuation has conflicting error"),+ ("cancel", "user requested", "shutdown", "cancelled continuation has conflicting error"),+ ],+)+def test_continuation_record_terminal_replay_rejects_conflicts_without_mutation(+ terminal_method: str,+ value: object,+ conflicting_value: object,+ error: str,+) -> None:+ continuation = ContinuationRecord(+ continuation_id="continuation",+ owner_id="owner",+ frame=_frame(),+ kind="child",+ )+ continuation.start()+ transition = getattr(continuation, terminal_method)++ assert transition(value) is True+ terminal_state = continuation.model_dump(mode="python")++ assert transition(value) is False+ assert continuation.model_dump(mode="python") == terminal_state++ with pytest.raises(ValueError, match=error):+ transition(conflicting_value)+ assert continuation.model_dump(mode="python") == terminal_state++def test_continuation_record_rejects_invalid_transition_without_mutation() -> None:continuation = ContinuationRecord(continuation_id="continuation",diff --git a/tests/app/services/shared/test_execution_snapshot_integrity.py b/tests/app/services/shared/test_execution_snapshot_integrity.pynew file mode 100644index 0000000000..3a0e50fb64--- /dev/null+++ b/tests/app/services/shared/test_execution_snapshot_integrity.py@@ -0,0 +1,173 @@+from copy import deepcopy+from unittest.mock import MagicMock++import pytest++from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation+from invokeai.app.services.shared.execution_effects import (+ ExecutionEffectsRecorder,+ ExecutionInterface,+)+from invokeai.app.services.shared.execution_state_migration import dump_execution_state, load_execution_state+from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph, GraphExecutionState+from invokeai.app.services.shared.invocation_context import InvocationContext+++def _context() -> InvocationContext:+ context = object.__new__(InvocationContext)+ context.execution_effects = ExecutionEffectsRecorder()+ context.effects = context.execution_effects+ return context+++def _services() -> MagicMock:+ services = MagicMock()+ services.configuration.node_cache_size = 1+ return services+++def _apply_flat_for_pair(*, apply_return: bool = True) -> GraphExecutionState:+ 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 isinstance(return_invocation, ForReturnInvocation)+ 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())+ if apply_return:+ state.apply(+ state.get_execution_ref(return_invocation.id, effect_count=len(return_result.effects)), return_result+ )+ return state+++def _execution_id(state: GraphExecutionState, source_id: str) -> str:+ return next(+ exec_id for exec_id, mapped_source_id in state.prepared_source_mapping.items() if mapped_source_id == source_id+ )++[email protected]("bucket_mode", ["missing", "empty"])+def test_rejects_tampered_for_result_without_effect_bucket(bucket_mode: str) -> None:+ state = _apply_flat_for_pair()+ for_exec_id = _execution_id(state, "for")+ for_ref = state.get_execution_ref(for_exec_id)+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["results"][for_exec_id]["item"] = "forged"+ if bucket_mode == "missing":+ snapshot["execution_effects"].pop(for_ref.reference_id)+ else:+ snapshot["execution_effects"][for_ref.reference_id] = []++ with pytest.raises(ValueError):+ load_execution_state(snapshot)+++ ("field", "value"),+ [+ ("output_collection", ["forged"]),+ ("final_state", {"values": {"forged": True}}),+ ],+)+def test_rejects_tampered_completed_for_outputs(field: str, value: object) -> None:+ state = _apply_flat_for_pair()+ for_exec_id = _execution_id(state, "for")+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["results"][for_exec_id][field] = value++ with pytest.raises(ValueError, match="For output .* authoritative"):+ load_execution_state(snapshot)+++def test_rejects_empty_effect_bucket_for_pending_execution() -> None:+ state = _apply_flat_for_pair(apply_return=False)+ return_exec_id = _execution_id(state, "return")+ return_ref = state.get_execution_ref(return_exec_id)+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["execution_effects"][return_ref.reference_id] = []++ with pytest.raises(ValueError, match="pending execution node"):+ load_execution_state(snapshot)+++def test_rejects_effect_bucket_without_executed_marker() -> None:+ state = _apply_flat_for_pair()+ for_exec_id = _execution_id(state, "for")+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["executed"].remove(for_exec_id)++ with pytest.raises(ValueError, match="executed marker"):+ load_execution_state(snapshot)+++def test_rejects_unknown_effect_bucket_reference() -> None:+ state = _apply_flat_for_pair()+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["execution_effects"]["unknown-reference"] = []++ with pytest.raises(ValueError, match="unknown execution reference"):+ load_execution_state(snapshot)++[email protected]("source_id", ["for", "return"])+def test_rejects_persisted_loop_result_without_required_continuation_effect(source_id: str) -> None:+ state = _apply_flat_for_pair()+ exec_id = _execution_id(state, source_id)+ execution_ref = state.get_execution_ref(exec_id)+ snapshot = deepcopy(dump_execution_state(state))+ snapshot["execution_effects"].pop(execution_ref.reference_id)++ with pytest.raises(ValueError, match="must include a continuation effect"):+ load_execution_state(snapshot)+++def test_accepts_explicit_legacy_snapshot_without_effect_ledger() -> None:+ state = _apply_flat_for_pair()+ snapshot = dump_execution_state(state)+ snapshot.pop("execution_state_version")+ snapshot.pop("execution_effects")++ restored = load_execution_state(snapshot)++ assert restored.results == state.results+ assert restored.execution_effects == {}