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
refactor(execution): route saved workflow calls through effects
JPPhoto02d1cf6ecfc8
diff --git a/docs/src/content/docs/contributing/call-saved-workflow.md b/docs/src/content/docs/contributing/call-saved-workflow.mdindex 6af3968f99..782ad8e72f 100644--- a/docs/src/content/docs/contributing/call-saved-workflow.md+++ b/docs/src/content/docs/contributing/call-saved-workflow.md@@ -17,13 +17,16 @@ The long-term feature goal is:- The architecture must work for Invoke frontend graphs and for externally submitted graphs that use the same node type.This document records the current state, the target architecture, and the execution contract needed to continue-development later.+development later. The target is not the current scheduler shape: saved-workflow calls still use a dedicated queue+boundary for durable rows and queue transitions, while the invocation and graph state now use the generic lifecycle+effect/dependency seam to declare, persist, and resume the call.The execution-engine refactoring does not change the callable node, saved-workflow, or queue interaction contract.-Generated API schemas may be regenerated when backend runtime metadata becomes visible in a response, but existing-fields, requiredness, statuses, events, and client behavior remain compatible. Frontend application behavior is outside-this execution-engine slice. No code under `invokeai/frontend/...` may be changed by this refactoring; the existing-frontend/backend external interface is frozen.+Internal execution references, tokens, effects, frames, and scheduler records are persistence-only implementation+metadata. They must remain out of ordinary client-facing responses and generated client schemas. Existing fields,+requiredness, statuses, events, and client behavior remain compatible. Frontend application behavior is outside this+execution-engine slice. No code under `invokeai/frontend/...`, including generated `openapi.json` or `schema.ts`, may be+changed by this refactoring; the existing frontend/backend external interface is frozen.The internal generic boundary is implemented in`invokeai.app.services.shared.execution_engine`. It provides frame-scoped@@ -90,15 +93,19 @@ Implemented runtime scaffolding:- child sessions carry a `workflow_call_parent` reference back to the parent call relationship- `GraphExecutionState.next()` returns no runnable node while the parent session is waiting on a child workflow call.- `GraphExecutionState.is_complete()` stays false while waiting.-- `DefaultSessionRunner.run_node()` now treats `call_saved_workflow` as a call boundary instead of a normal executable- node.-- On boundary entry, the runner:- - validates the selected workflow- - builds a workflow call frame- - converts the saved workflow JSON into a backend `Graph`- - validates and applies parent call arguments to the child graph- - creates a child `GraphExecutionState`- - attaches that child session to the waiting parent session+- `DefaultSessionRunner.run_node()` invokes `call_saved_workflow` through the same effect-aware invocation path as+ other nodes. The invocation records one capability-bound `spawn_execution` effect and one matching `await` effect;+ authorization and input collection happen before those effects are recorded.+- `GraphExecutionState.apply()` persists the pending lifecycle effects without completing the call node. The queue+ adapter then consumes the effects to:+ - build a workflow call frame+ - convert the saved workflow JSON into a backend `Graph`+ - validate and apply parent call arguments to the child graph+ - create child `GraphExecutionState` instances and durable child queue rows+ - attach those child sessions to the waiting parent session+- When the generic child dependency reaches a terminal result, the queue adapter projects the legacy workflow-call+ fields, resumes the parent through `GraphExecutionState.apply()`, and completes the call node with ordered return+ values. A capability-gated `fail` effect records a parent failure without creating child rows.- Workflow-call runtime responsibilities are now split:- `WorkflowCallCoordinator` handles call-specific setup:- build the child graph@@ -311,8 +318,9 @@ Current limitation:- connected batch child inputs produced by ordinary non-generator upstream nodes are still not supported and should failearly with a clear unsupported-feature error- the current queue-visible child execution path still relies on `WorkflowCallCoordinator` and- `WorkflowCallQueueLifecycle` to resume or fail parents; the generic child record supplies the identity and- aggregation boundary without changing the public queue contract+ `WorkflowCallQueueLifecycle` for durable row creation and parent transitions; generic lifecycle effects and+ `ChildDependencyRecord` supply the invocation intent, identity, ordered aggregation, idempotency, and terminal+ decision without changing the public queue contract### 4a. Queue Lifecycle Contract@@ -586,7 +594,7 @@ Current insertion points already used:Next runtime work still needed:-- keep `WorkflowCallQueueLifecycle` as the bounded workflow-call lifecycle component for this PR+- keep `WorkflowCallQueueLifecycle` as the bounded workflow-call lifecycle component for this refactor- the current workflow-call feature is the only caller of parent/child queue semantics- replacing it with a generalized queue dependency scheduler now would add regression risk without unlocking aconcrete user workflow@@ -746,9 +754,10 @@ Tests first:### Stage 5: Frontend Schema, UI, And Docs-Status: mostly implemented. Schema/type generation includes the backend nodes and fields; editor connection coverage and-localized UI strings are in place for the current node wiring. Future UX cleanup should be driven by concrete user-testing rather than added as speculative work.+Status: mostly implemented. Existing schema/type generation includes the backend nodes and fields; editor connection+coverage and localized UI strings are in place for the current node wiring. This describes the callable-workflow+feature baseline, not a request to regenerate or change frontend artifacts as part of the execution-engine refactor.+Future UX cleanup should be driven by concrete user testing rather than added as speculative work.Goal:diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex d62b9a2ec3..66d34bb9d7 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -5,6 +5,34 @@ title: Loop Nodes ArchitectureThis page records the implementation contract for the collection-based `For` and `ForReturn` nodes. The durablecontract is shared by the backend graph executor, saved workflow format, and workflow editor.+## Current execution-engine shape++The author-time graph contract is unchanged. `GraphExecutionState` remains the execution façade: it owns graph+validation, prepared execution-node identity, frame and iteration-path metadata, persistence, and the boundary between+invocation results and scheduling.++Readiness is split by admitted topology:++- `ExecutionPlan` and `ExecutionScheduler` provide opaque, deterministic node readiness and completion. They do not+ choose successors by node type or accept literal successor-node IDs.+- `_GenericGraphSchedulerAdapter` projects existing graph state into that scheduler for admitted fresh graphs and for+ the ordinary static-DAG/legacy compatibility path.+- `_GenericForPlanner`, the bounded `Iterate` planners, and the frame-scoped `If` dependency code supply the+ control-flow-specific preparation and activation rules for their exact admitted shapes.+- `_ExecutionMaterializer` remains the compatibility owner for unsupported topologies and legacy snapshots.+- `CallSavedWorkflowInvocation` declares one capability-bound `spawn_execution` plus matching `await` effect (or a+ capability-bound `fail`). `GraphExecutionState` persists the pending lifecycle effects and generic child dependency;+ `WorkflowCallCoordinator` and `WorkflowCallQueueLifecycle` remain the durable owner of saved-workflow child queue+ rows, statuses, events, authorization, capacity, cancellation, recovery, retry, and parent/child projection.++Control-flow nodes remain concrete `BaseInvocation` subclasses. They do not inherit from a new control-flow engine+hierarchy, and they do not return a literal next-node ID. Internal planners and records may share implementation+helpers, while successor readiness is selected from frame-scoped dependencies and effects.++This is an incremental hybrid, not yet a token-authoritative engine. The execution ledger and internal planners are+backend persistence details; they do not add author-time ports or change the frontend/backend external contract. No+file under `invokeai/frontend/...` is part of this refactoring.+## Core contract`For` is a bounded collection loop, not a general `While` node. Its source is one `collection: list[Any]` input. Each@@ -160,8 +188,8 @@ preserved across dump/load.For the exact fresh direct shape, the planner owns expansion, downstream admission, and empty closure atomically: afailed expansion leaves no partial prepared copies to be resumed. Versioned queue checkpoints and retries preserve the existing durableexecution-state boundary and receive fresh execution identities. Materialization still owns those responsibilities for-fallback shapes. Mixed control-flow and queue lifecycle remain compatibility-owned. `loop_linkage`-remains association metadata and never becomes a data token.+fallback shapes. Mixed control-flow outside the exact bounded admitted topology and queue lifecycle remain+compatibility-owned. `loop_linkage` remains association metadata and never becomes a data token.The supported flat-loop differential gate covers generic/compatibility parityfor successful execution, carried and replaced state, early break, empty and@@ -202,7 +230,8 @@ chain, or exactly two, exactly three, or exactly four independent ordinary-nodeactivation dependencies in graph state. The three- and four-`If` admissions require `default` edges, all branch inputs(`condition`, `true_input`, `false_input`) on each `If`, and no output from inner or middle `If` except its direct nestedbranch edge; the four-`If` chain permits no extra output fan-out. Five-or-more nested `If`s, other fan-out, mixed-shapes outside the bounded per-item `Iterate`/`If`/`Collect` topology, loop-containing, saved-workflow, legacy, and+shapes outside the bounded per-item `Iterate`/`If`/`Collect` topology, loop-containing `For`/`ForReturn`, saved-workflow,+legacy, andfive-or-more sibling shapes use the compatibility scheduler with the dedicated`_IfActivationController` fallback. Legacy snapshots retain their generic compatibilityprojection. Legacy@@ -220,8 +249,9 @@ their compatibility paths until differential coverage proves their generic replaThe engine keeps compatibility materialization and queue readiness for loop-containing graphs outside the migrationmatrix and for existing snapshots. Admitted fresh `For` graphs use the generic opaque plan/scheduler plus`_GenericForPlanner`; `_ExecutionNodeBuilder` supplies shared low-level graph mutation mechanics. Ordinary static DAGs,-legacy-shaped `If` graphs, and direct `Iterate`/`Collect`-only graphs retain their existing generic or compatibility-routes. No activation, stream, or continuation ports are added to author-time graph JSON.+supported fresh `If` graphs, direct `Iterate`/`Collect`-only graphs, and the exact bounded mixed+`Iterate`/`If`/`Collect` graph use the generic adapter; unsupported or legacy shapes retain their compatibility routes.+No activation, stream, or continuation ports are added to author-time graph JSON.Exact fresh serial nested-`Iterate` chains through eight levels use the generic planner for ordered frame expansion,empty-stream closure, checkpoint rehydration, source completion, and failure parity. Nine-level or deeper chains,five-level-or-deeper or unsupported sibling nested loops, and unsupported mixed shapes remain compatibility-owned. The exact fresh two-sibling `For`/`ForReturn` `CollectionConcat` fan-in shape, the exact fresh three-level serial nested-`For` shape with its bounded static `CollectionConcat` producer, and the exact fresh four-level serial nested-`For` shape are generic-routed. This migration does not modify any file under `invokeai/frontend/...`, including generated schemas; the existingdiff --git a/invokeai/app/invocations/call_saved_workflow.py b/invokeai/app/invocations/call_saved_workflow.pyindex 36f03021b1..a68488c6e9 100644--- a/invokeai/app/invocations/call_saved_workflow.py+++ b/invokeai/app/invocations/call_saved_workflow.py@@ -3,6 +3,7 @@ from typing import Anyfrom invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocationfrom invokeai.app.invocations.fields import InputField, UITypefrom invokeai.app.invocations.workflow_return import WorkflowReturnOutput+from invokeai.app.services.shared.execution_effects import ExecutionReffrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.app.services.workflow_records.workflow_records_common import WorkflowCategory, WorkflowNotFoundError@@ -37,6 +38,8 @@ def parse_call_saved_workflow_dynamic_input(field_name: str) -> tuple[str, str]:class CallSavedWorkflowInvocation(BaseInvocation):"""Displays and later executes against a selected saved workflow."""+ execution_effects_enabled = True+workflow_id: str = InputField(default="",description="The selected saved workflow ID, managed by the workflow editor UI.",@@ -70,6 +73,36 @@ class CallSavedWorkflowInvocation(BaseInvocation):return workflow_recorddef invoke(self, context: InvocationContext) -> WorkflowReturnOutput:- self.validate_selected_workflow(context)+ execution = getattr(context, "execution", None)+ lifecycle_enabled = (+ getattr(getattr(context, "execution_effects", None), "allow_lifecycle_effects", False) is True+ )+ if execution is None or not lifecycle_enabled:+ self.validate_selected_workflow(context)+ return WorkflowReturnOutput(values={})++ try:+ workflow_record = execution.authorize_workflow(self.workflow_id)+ workflow_inputs = context._data.execution_workflow_inputs+ if workflow_inputs is None:+ workflow_inputs = dict(self.workflow_inputs)+ child = execution.spawn(+ workflow_record.workflow.model_dump(mode="json"),+ dict(workflow_inputs),+ )+ execution.await_dependency(+ ExecutionRef(+ execution_node_id=child.child_execution_id,+ state_id=context._data.execution_state_id,+ frame_path=context._data.execution_frame,+ frame_id=context._data.execution_frame_id,+ workflow_call_depth=context._data.execution_workflow_call_depth,+ )+ )+ except Exception as e:+ if lifecycle_enabled:+ execution.fail(str(e))+ return WorkflowReturnOutput(values={})+ raisereturn WorkflowReturnOutput(values={})diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.pyindex fdfc7a539e..70435e58f1 100644--- a/invokeai/app/services/session_processor/session_processor_default.py+++ b/invokeai/app/services/session_processor/session_processor_default.py@@ -261,6 +261,42 @@ class DefaultSessionRunner(SessionRunnerBase):self._on_before_run_node(invocation, queue_item)execution_ref = queue_item.session.get_execution_ref(invocation.id)+ child_capability = None+ workflow_inputs = None+ workflow_authorizer = None+ if isinstance(invocation, CallSavedWorkflowInvocation):+ if not hasattr(queue_item.session, "build_child_execution_capability"):+ data = InvocationContextData(+ invocation=invocation,+ source_invocation_id=queue_item.session.prepared_source_mapping[invocation.id],+ queue_item=queue_item,+ execution_frame=execution_ref.frame.iteration_path,+ execution_state_id=execution_ref.state_id,+ execution_frame_id=execution_ref.frame.frame_id,+ execution_workflow_call_depth=execution_ref.frame.workflow_call_depth,+ )+ context = build_invocation_context(+ data=data,+ services=self._services,+ is_canceled=self._is_canceled,+ )+ workflow_record = invocation.validate_selected_workflow(context)+ self.workflow_call_coordinator.begin_workflow_call_boundary(+ invocation, queue_item, workflow_record+ )+ return+ child_capability = queue_item.session.build_child_execution_capability(+ execution_ref,+ authorization_context={"user_id": queue_item.user_id},+ )+ workflow_inputs = self.workflow_call_coordinator._collect_call_saved_workflow_inputs(+ invocation, queue_item+ )+ if isinstance(invocation, CallSavedWorkflowInvocation):++ def workflow_authorizer(_workflow_id: str):+ return invocation.validate_selected_workflow(context)+data = InvocationContextData(invocation=invocation,source_invocation_id=queue_item.session.prepared_source_mapping[invocation.id],@@ -269,6 +305,9 @@ class DefaultSessionRunner(SessionRunnerBase):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,+ execution_child_capability=child_capability,+ execution_workflow_authorizer=workflow_authorizer,+ execution_workflow_inputs=workflow_inputs,)context = build_invocation_context(data=data,@@ -276,7 +315,10 @@ class DefaultSessionRunner(SessionRunnerBase):is_canceled=self._is_canceled,)- if isinstance(invocation, CallSavedWorkflowInvocation):+ # Retain the queue boundary for compatibility contexts that cannot record lifecycle effects.+ if isinstance(invocation, CallSavedWorkflowInvocation) and not getattr(+ context.execution_effects, "allow_lifecycle_effects", False+ ):workflow_record = invocation.validate_selected_workflow(context)self.workflow_call_coordinator.begin_workflow_call_boundary(invocation, queue_item, workflow_record)return@@ -294,6 +336,31 @@ class DefaultSessionRunner(SessionRunnerBase):)finalized_outputs = queue_item.session.apply(execution_ref, run_result)+ if isinstance(invocation, CallSavedWorkflowInvocation):+ failure_effect = next(+ (effect for effect in run_result.effects if getattr(effect, "kind", None) == "fail"),+ None,+ )+ if failure_effect is not None:+ error_message = str(getattr(failure_effect, "message", "saved workflow call failed"))+ self._on_node_error(+ invocation=invocation,+ queue_item=queue_item,+ error_type="ValueError",+ error_message=error_message,+ error_traceback=error_message,+ )+ return++ workflow_record = invocation.validate_selected_workflow(context)+ self._dispatch_workflow_call_effects(+ invocation=invocation,+ queue_item=queue_item,+ workflow_record=workflow_record,+ effects=run_result.effects,+ )+ return+if control_collection is not None:invocation.collection = control_collectiontry:@@ -331,6 +398,29 @@ class DefaultSessionRunner(SessionRunnerBase):error_traceback=error_traceback,)+ def _dispatch_workflow_call_effects(+ self,+ *,+ invocation: CallSavedWorkflowInvocation,+ queue_item: SessionQueueItem,+ workflow_record,+ effects,+ ) -> None:+ """Pass lifecycle intent through queue adapter, retaining old boundary fallback."""++ hook = getattr(self.workflow_call_queue_lifecycle, "apply_execution_effects", None)+ if hook is None:+ hook = getattr(self.workflow_call_coordinator, "apply_execution_effects", None)+ if hook is not None:+ hook(+ invocation=invocation,+ queue_item=queue_item,+ workflow_record=workflow_record,+ effects=effects,+ )+ return+ self.workflow_call_coordinator.begin_workflow_call_boundary(invocation, queue_item, workflow_record)+@contextmanagerdef _maybe_offload_to_idle_gpu(self, invocation: BaseInvocation) -> Iterator[None]:"""Temporarily re-pin this worker thread to an idle GPU for a text-encoder node.diff --git a/invokeai/app/services/session_processor/workflow_call_runtime.py b/invokeai/app/services/session_processor/workflow_call_runtime.pyindex 59ddcb118a..f39ee6629a 100644--- a/invokeai/app/services/session_processor/workflow_call_runtime.py+++ b/invokeai/app/services/session_processor/workflow_call_runtime.py@@ -71,6 +71,10 @@ class WorkflowCallCoordinator:invocation: CallSavedWorkflowInvocation,queue_item: SessionQueueItem,workflow_record,+ *,+ workflow: Any | None = None,+ workflow_inputs: dict[str, Any] | None = None,+ dependency_id: str | None = None,) -> SessionQueueItem:queue_status = self._session_runner._services.session_queue.get_queue_status(queue_item.queue_id)remaining_queue_capacity = self._session_runner._services.configuration.max_queue_size - queue_status.pending@@ -78,10 +82,13 @@ class WorkflowCallCoordinator:raise ValueError("call_saved_workflow exceeds remaining queue capacity for child workflow executions")call_frame = queue_item.session.build_workflow_call_frame(invocation.id, invocation.workflow_id)- workflow_inputs = self._collect_call_saved_workflow_inputs(invocation, queue_item)+ if workflow is None:+ workflow = workflow_record.workflow.model_dump()+ if workflow_inputs is None:+ workflow_inputs = self._collect_call_saved_workflow_inputs(invocation, queue_item)child_session_results = build_child_workflow_session_results(parent_session=queue_item.session,- workflow=workflow_record.workflow.model_dump(),+ workflow=workflow,workflow_inputs=workflow_inputs,call_frame=call_frame,maximum_children=remaining_queue_capacity,@@ -91,7 +98,13 @@ class WorkflowCallCoordinator:child_sessions = [child_result.session for child_result in child_session_results]if len(child_sessions) > remaining_queue_capacity:raise ValueError("call_saved_workflow exceeds remaining queue capacity for child workflow executions")+ if dependency_id is not None and (not isinstance(dependency_id, str) or not dependency_id.strip()):+ raise ValueError("Workflow call dependency id must not be blank.")queue_item.session.begin_waiting_on_workflow_call(call_frame)+ if dependency_id is not None:+ if queue_item.session.waiting_workflow_call_execution is None:+ raise ValueError("Execution state is waiting on a workflow call but has no execution metadata.")+ queue_item.session.waiting_workflow_call_execution.id = dependency_idqueue_item.session.attach_waiting_workflow_call_child_sessions(child_sessions)child_queue_item = Noneenqueued_child_item_ids: list[int] = []@@ -124,6 +137,89 @@ class WorkflowCallQueueLifecycle:def __init__(self, session_runner: DefaultSessionRunner) -> None:self._session_runner = session_runner+ @staticmethod+ def _effect_value(effect: Any, name: str, default: Any = None) -> Any:+ if isinstance(effect, dict):+ return effect.get(name, default)+ return getattr(effect, name, default)++ @classmethod+ def _effect_kind(cls, effect: Any) -> Any:+ return next(+ (+ cls._effect_value(effect, name)+ for name in ("kind", "effect_type", "type")+ if cls._effect_value(effect, name) is not None+ ),+ None,+ )++ def apply_execution_effects(+ self,+ *,+ invocation: CallSavedWorkflowInvocation,+ queue_item: SessionQueueItem,+ workflow_record,+ effects,+ ) -> None:+ """Apply call lifecycle effects through durable queue workflow-call semantics."""++ lifecycle_effects = [+ effect for effect in effects if self._effect_kind(effect) in {"spawn_execution", "await", "fail"}+ ]+ spawn_effects = [effect for effect in lifecycle_effects if self._effect_kind(effect) == "spawn_execution"]+ await_effects = [effect for effect in lifecycle_effects if self._effect_kind(effect) == "await"]+ fail_effects = [effect for effect in lifecycle_effects if self._effect_kind(effect) == "fail"]++ if fail_effects:+ if len(fail_effects) != 1 or spawn_effects or await_effects:+ raise ValueError(+ "Workflow call lifecycle effects must contain either one fail or one spawn+await pair."+ )+ message = self._effect_value(fail_effects[0], "message")+ if not isinstance(message, str) or not message.strip():+ raise ValueError("Workflow call fail effect requires an error message.")+ raise ValueError(message)++ if len(spawn_effects) != 1 or len(await_effects) != 1:+ raise ValueError("Workflow call lifecycle effects must contain exactly one spawn and one await effect.")++ spawn_effect = spawn_effects[0]+ await_effect = await_effects[0]+ child_execution_id = self._effect_value(spawn_effect, "child_execution_id")+ if not isinstance(child_execution_id, str) or not child_execution_id.strip():+ raise ValueError("Workflow call spawn effect requires a child execution identity.")++ dependency = self._effect_value(await_effect, "dependency")+ awaited_child_id = next(+ (+ self._effect_value(dependency, name)+ for name in ("execution_node_id", "child_execution_id", "execution_id", "node_id", "child_id")+ if self._effect_value(dependency, name) is not None+ ),+ None,+ )+ if awaited_child_id != child_execution_id:+ raise ValueError("Workflow call await effect does not match its spawn effect.")++ workflow = self._effect_value(spawn_effect, "graph")+ if hasattr(workflow, "model_dump"):+ workflow = workflow.model_dump(mode="json")+ if not isinstance(workflow, dict):+ raise ValueError("Workflow call spawn effect requires a workflow graph.")+ workflow_inputs = self._effect_value(spawn_effect, "inputs")+ if not isinstance(workflow_inputs, dict):+ raise ValueError("Workflow call spawn effect requires workflow inputs.")++ self._session_runner.workflow_call_coordinator.begin_workflow_call_boundary(+ invocation,+ queue_item,+ workflow_record,+ workflow=workflow,+ workflow_inputs=dict(workflow_inputs),+ dependency_id=child_execution_id,+ )+@staticmethoddef get_waiting_workflow_call_invocation(queue_item: SessionQueueItem) -> CallSavedWorkflowInvocation:waiting_frame = queue_item.session.waiting_workflow_call@@ -205,17 +301,25 @@ class WorkflowCallQueueLifecycle:generic_update = parent_queue_item.session.record_generic_child_completion(child_queue_item.item_id, output.values)- should_resume_parent, aggregated_values = (+ if generic_update is not None and not generic_update.changed:+ return+ # Keep legacy fields as a durable projection. Generic dependency state owns+ # ordering, idempotency, readiness, and aggregated output decisions.+ legacy_should_resume, legacy_values = (parent_queue_item.session.record_waiting_workflow_call_child_completion(child_queue_item.item_id, output.values))- if generic_update is not None and generic_update.status == "completed":+ if generic_update is None:+ should_resume_parent, aggregated_values = legacy_should_resume, legacy_values+ else:+ should_resume_parent = generic_update.status == "completed"generic_values = {key: values[0] if len(values) == 1 else valuesfor key, values in generic_update.aggregated_outputs.items()}- if generic_values != aggregated_values:+ aggregated_values = generic_values+ if generic_update.status == "completed" and generic_values != legacy_values:raise ValueError("Generic child aggregation disagrees with workflow-call aggregation.")except Exception as e:workflow_call_execution = parent_queue_item.session.waiting_workflow_call_execution@@ -270,8 +374,11 @@ class WorkflowCallQueueLifecycle:f"The selected saved workflow '{waiting_frame.workflow_id}' failed during child execution.")workflow_call_execution = parent_queue_item.session.waiting_workflow_call_execution+ generic_update = Noneif workflow_call_execution is not None:- parent_queue_item.session.fail_generic_child(child_queue_item.item_id, child_error_message)+ generic_update = parent_queue_item.session.fail_generic_child(child_queue_item.item_id, child_error_message)+ if generic_update is not None and generic_update.status != "failed":+ returnself._session_runner._services.session_queue.cancel_workflow_call_children(workflow_call_execution.id,exclude_item_ids={child_queue_item.item_id},@@ -288,7 +395,13 @@ class WorkflowCallQueueLifecycle:parent_queue_item = self._get_parent_queue_item(child_queue_item)if parent_queue_item is None or parent_queue_item.status == "canceled":return- parent_queue_item.session.cancel_generic_child(child_queue_item.item_id, "child canceled")+ generic_update = parent_queue_item.session.cancel_generic_child(child_queue_item.item_id, "child canceled")+ if generic_update is not None and generic_update.status != "canceled":+ return+ if generic_update is not None:+ self._session_runner._services.session_queue.save_queue_item_session(+ parent_queue_item.item_id, parent_queue_item.session+ )self._session_runner._services.session_queue.cancel_queue_item(parent_queue_item.item_id)def run_queue_item(self, queue_item: SessionQueueItem) -> None:diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 481f5284b3..1de97cdf98 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -55,11 +55,11 @@ The bounded If evidence rerun on the current branch passes 639 tests acrossthe differential, dependency, runtime, SQLite processor, and snapshotmigration suites. This is focused migration evidence, not a full-suite result;the controller fallback and legacy projection remain intentional.-The execution ledgers (`execution_refs`, `execution_tokens`, and-`execution_effects`) are internal persistence data. They are excluded from-ordinary model/API serialization and schemas; `dump_execution_state()` is the-explicit internal persistence path that retains them, including nested child-states.+The execution ledgers (`execution_refs`, `execution_tokens`, `execution_effects`,+and `execution_child_dependencies`) are internal persistence data. They are+not part of public API schemas or client responses; `dump_execution_state()`+is the explicit internal persistence path that retains them, including nested+child states.Direct `Iterate`/`Collect` graphs that do not contain `If`, `For`, `ForReturn`, or saved-workflow control flow also usethe generic adapter. Its adapter-level readiness predicate waits for canonical Iterate streams to close, and genericcompletion mirrors each Iterate result into that ledger before releasing `Collect`. The exact fresh four-node shape@@ -359,7 +359,8 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre`For` shape, the exact fresh three-level and four-level serial nested-`For` shapes (including the exact three-level producer-driven outer variant), the exact producer-driven nested extension, the exact bounded empty input-driven flat `For`, the boundedtwo- through eight-level serial nested-`Iterate` chains, and the bounded per-item `Iterate`/`If`/`Collect` topology usethe generic adapter for readiness and continuation projection; other unsupported input-driven, nine-level or deeper,- mixed graphs outside that topology, and saved-workflow graphs retain the legacy scheduler. Optional+ mixed graphs outside that topology retain the legacy scheduler, while saved-workflow calls use the generic lifecycle+ effect/dependency projection with the dedicated durable queue adapter. Optional`ready_order: list[str]` prioritizes classes. Queues are rebuilt from persisted execution state when a session isdeserialized.@@ -555,9 +556,11 @@ Workflow-call note:- `GraphExecutionState` can represent a paused parent execution plus an attached child execution state, but it does notitself orchestrate child execution.-- In the current implementation, `DefaultSessionRunner.run_node()` establishes the workflow call boundary and attaches- the child execution state, while `WorkflowCallCoordinator` handles call-specific setup and- `WorkflowCallQueueLifecycle` later resumes or fails the parent based on that child queue row's outcome.+- In the current implementation, `DefaultSessionRunner.run_node()` invokes `CallSavedWorkflowInvocation` through the+ effect-aware path. The invocation records capability-bound `spawn_execution` plus `await` (or `fail`) intent;+ `GraphExecutionState.apply()` persists the pending batch, `WorkflowCallCoordinator` handles durable child setup,+ and `WorkflowCallQueueLifecycle` later resumes or fails the parent based on the generic child dependency and child+ queue outcome.- Child `SessionQueueItem` rows created by the coordinator now carry explicit relationship metadata such as`workflow_call_id`, `parent_item_id`, `parent_session_id`, `root_item_id`, and `workflow_call_depth`, even though thehigher-level scheduler semantics are still evolving.@@ -579,10 +582,10 @@ Workflow-call note:- child queue-row creation is cleaned up on boundary-setup failure and child fan-out is bounded by remaining queuecapacity- child workflows that mix supported batch nodes with unrelated generator nodes are rejected for now-- The generic `ChildDependencyRecord` adapter now validates the same waiting parent, ordered children, capability- identity, all-of aggregation, resource limits, and terminal transitions alongside this workflow-call lifecycle.- Existing queue fields, statuses, cancellation, retry, and event behavior remain authoritative; queue-row creation and- recovery are not silently delegated to an in-memory record.+- The generic `ChildDependencyRecord` now owns the internal child identity, ordered all-of aggregation, capability+ identity, resource limits, idempotent terminal transition, and parent terminal decision alongside this workflow-call+ lifecycle. Existing queue fields, statuses, cancellation, retry, and event behavior remain authoritative; queue-row+ creation and recovery are not silently delegated to an in-memory record.### 4.3 Runtime helper classes@@ -802,8 +805,9 @@ In normal execution, all runtime expansion occurs in `execution_graph` with trac- **Scheduling policy**: adjust `ready_order` to prioritize class queues. A batch-size or fairness cap is not currentlyimplemented.- **Dynamic behaviors**: effect-enabled invocations may record frame-scoped stream, activation, and authorized child- lifecycle intent. `GraphExecutionState.apply()` remains the transactional graph boundary and rejects mutation or- queue effects unless a matching adapter owns their application.+ lifecycle intent. `GraphExecutionState.apply()` remains the transactional graph boundary: it persists a pending+ saved-workflow lifecycle batch and generic child dependency, while the matching queue adapter owns durable row+ creation and queue transitions. Mutation effects remain rejected.- **Workflow call boundaries**: `GraphExecutionState` can suspend a parent execution state on a workflow call, attach achild execution state, and later resume the parent without mutating the source graph.diff --git a/invokeai/app/services/shared/execution_state_migration.py b/invokeai/app/services/shared/execution_state_migration.pyindex 434480cd9d..15f74dd7ed 100644--- a/invokeai/app/services/shared/execution_state_migration.py+++ b/invokeai/app/services/shared/execution_state_migration.py@@ -37,6 +37,10 @@ def _append_runtime_fields(snapshot: dict[str, Any], state: GraphExecutionState)]for reference_id, effects in state.execution_effects.items()}+ snapshot["execution_child_dependencies"] = {+ dependency_id: dependency.model_dump(mode="json", warnings=False)+ for dependency_id, dependency in state.execution_child_dependencies.items()+ }for reference_id, effects in state._legacy_execution_effects_for_snapshot().items():snapshot["execution_effects"][reference_id] = [effect.model_dump(mode="json") if hasattr(effect, "model_dump") else effect for effect in effectsdiff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 2116d6710e..431727920c 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -185,7 +185,9 @@ from invokeai.app.util.misc import uuid_string_JSON_SERIALIZER = TypeAdapter(Any)-_EXECUTION_STATE_RUNTIME_FIELDS = frozenset({"execution_refs", "execution_tokens", "execution_effects"})+_EXECUTION_STATE_RUNTIME_FIELDS = frozenset(+ {"execution_refs", "execution_tokens", "execution_effects", "execution_child_dependencies"}+)_EXECUTION_STATE_REQUIRED_FIELDS = ("id","graph",@@ -298,6 +300,11 @@ class GraphExecutionState(BaseModel):default_factory=dict,description="Effects accepted for each execution reference",)+ execution_child_dependencies: dict[str, ChildDependencyRecord] = Field(+ default_factory=dict,+ description="Durable generic child dependency records",+ exclude=True,+ )# Ready queues grouped by node class name (internal only)_ready_queues: dict[str, Deque[str]] = PrivateAttr(default_factory=dict)_ready_node_ids: set[str] = PrivateAttr(default_factory=set)@@ -1815,11 +1822,38 @@ class GraphExecutionState(BaseModel):return Noneexisting = self._generic_child_dependencies.get(execution.id)if existing is not None:+ expected_ref = self.execution_refs.get(execution.prepared_call_node_id)+ if expected_ref is None:+ expected_ref = self._expected_execution_ref(execution.prepared_call_node_id)+ if (+ existing.parent_execution_id != expected_ref.exec_node_id+ or existing.parent_reference_id != expected_ref.reference_id+ or existing.parent_frame != expected_ref.frame.iteration_path+ or existing.child_execution_ids != [str(item_id) for item_id in execution.child_item_ids]+ ):+ raise ValueError("Child dependency does not belong to active workflow call")return existing- parent_reference_id = f"{self.id}:{execution.prepared_call_node_id}"+ persisted = self.execution_child_dependencies.get(execution.id)+ if persisted is not None:+ expected_ref = self.execution_refs.get(execution.prepared_call_node_id)+ if expected_ref is None:+ expected_ref = self._expected_execution_ref(execution.prepared_call_node_id)+ if (+ persisted.parent_execution_id != expected_ref.exec_node_id+ or persisted.parent_reference_id != expected_ref.reference_id+ or persisted.parent_frame != expected_ref.frame.iteration_path+ or persisted.child_execution_ids != [str(item_id) for item_id in execution.child_item_ids]+ ):+ raise ValueError("Persisted child dependency does not belong to active workflow call")+ self._generic_child_dependencies[execution.id] = persisted+ return persisted+ execution_ref = self.execution_refs.get(execution.prepared_call_node_id)+ if execution_ref is None:+ execution_ref = self._expected_execution_ref(execution.prepared_call_node_id)+ parent_reference_id = execution_ref.reference_idcapability = ChildExecutionCapability(- parent_execution_id=self.id,- parent_frame=(),+ parent_execution_id=execution_ref.exec_node_id,+ parent_frame=execution_ref.frame.iteration_path,parent_reference_id=parent_reference_id,depth=max(execution.depth - 1, 0),max_depth=max(self.max_workflow_call_depth, execution.depth),@@ -1835,8 +1869,32 @@ class GraphExecutionState(BaseModel):if output_values is not None:record.complete_child(str(child_item_id), output_values)self._generic_child_dependencies[execution.id] = record+ self.execution_child_dependencies[execution.id] = recordreturn record+ def build_child_execution_capability(+ self,+ execution_ref: ExecutionReference,+ *,+ authorization_context: dict[str, Any] | None = None,+ max_children: int = 1,+ ) -> ChildExecutionCapability:+ """Issue lifecycle authority bound to one prepared node and exact frame."""++ ref = self._validate_execution_ref(execution_ref)+ if max_children < 1:+ raise ValueError("max_children must be at least one")+ return ChildExecutionCapability(+ parent_execution_id=ref.exec_node_id,+ parent_frame=ref.frame.iteration_path,+ parent_reference_id=ref.reference_id,+ authorization_context=authorization_context,+ depth=ref.frame.workflow_call_depth,+ max_depth=self.max_workflow_call_depth,+ max_children=max_children,+ capacity=max_children,+ )+def record_generic_child_completion(self, child_item_id: int, output_values: dict[str, Any]) -> ChildDependencyUpdate | None:@@ -2172,12 +2230,69 @@ class GraphExecutionState(BaseModel):continuation_payloads: dict[tuple[str, str], str] = {}duplicate_continuations: set[tuple[str, str]] = set()continuation_operations: set[str] = set()+ spawned_child_ids: set[str] = set()+ awaited_child_ids: list[str] = []+ lifecycle_effect_kinds: set[str] = set()for effect in effects:try:_JSON_SERIALIZER.dump_python(effect, mode="json", warnings="error")except (PydanticSerializationError, TypeError, ValueError) as exc:raise ValueError("Execution effect must be JSON-serializable") from exceffect_kind = self._value_from_object(effect, "kind", "effect_type", "type")+ if effect_kind in {"spawn_execution", "await", "fail"}:+ lifecycle_effect_kinds.add(effect_kind)+ lifecycle_owner = self._value_from_object(effect, "execution_ref", "execution_reference")+ if lifecycle_owner is not None:+ owner_reference_id = self._value_from_object(lifecycle_owner, "reference_id", "id")+ if owner_reference_id not in (None, "", execution_ref.reference_id):+ raise ValueError("Lifecycle effect belongs to another execution reference")+ owner_state_id = self._value_from_object(lifecycle_owner, "state_id", "session_id")+ if owner_state_id not in (None, "", execution_ref.state_id):+ raise ValueError("Lifecycle effect belongs to another graph execution state")+ self._validate_execution_frame(+ self._value_from_object(lifecycle_owner, "frame", "frame_path"),+ execution_ref,+ "Lifecycle effect",+ )+ owner_frame_id = self._value_from_object(lifecycle_owner, "frame_id")+ if owner_frame_id not in (None, "", execution_ref.frame.frame_id):+ raise ValueError("Lifecycle effect belongs to another execution frame")+ owner_depth = self._value_from_object(lifecycle_owner, "workflow_call_depth", "call_depth", "depth")+ if owner_depth not in (None, execution_ref.frame.workflow_call_depth):+ raise ValueError("Lifecycle effect belongs to another workflow-call depth")+ if effect_kind == "spawn_execution":+ child_execution_id = self._value_from_object(effect, "child_execution_id", "child_id")+ if not isinstance(child_execution_id, str) or not child_execution_id.strip():+ raise ValueError("Spawn effect requires a child execution identity")+ if child_execution_id in spawned_child_ids:+ raise ValueError("Spawn effect repeats a child execution identity")+ spawned_child_ids.add(child_execution_id)+ parent = self._value_from_object(effect, "parent")+ if parent is None or not self._same_execution_owner(parent, execution_ref):+ raise ValueError("Spawn effect parent is not owned by execution reference")+ self._validate_execution_frame(+ self._value_from_object(parent, "frame", "frame_path"),+ execution_ref,+ "Spawn effect parent",+ )+ elif effect_kind == "await":+ dependency = self._value_from_object(effect, "dependency")+ child_execution_id = self._value_from_object(+ dependency,+ "execution_node_id",+ "exec_node_id",+ "node_id",+ "child_execution_id",+ "execution_id",+ )+ if not isinstance(child_execution_id, str) or not child_execution_id.strip():+ raise ValueError("Await effect requires a child execution identity")+ awaited_child_ids.append(child_execution_id)+ elif effect_kind == "fail":+ message = self._value_from_object(effect, "message")+ if not isinstance(message, str) or not message.strip():+ raise ValueError("Fail effect requires an error message")+token = self._value_from_object(effect, "token")token_port = self._value_from_object(token, "field", "port", "output", "output_name")preliminary_port = self._value_from_object(effect, "source_port", "output_port", "source_field", "port")@@ -2272,7 +2387,8 @@ class GraphExecutionState(BaseModel):if owner is None or not self._same_execution_owner(owner, execution_ref):raise ValueError("Execution effect is not owned by execution reference")if effect_kind is not None and (- not isinstance(effect_kind, str) or effect_kind not in {"emit", "close_stream", "continuation"}+ not isinstance(effect_kind, str)+ or effect_kind not in {"emit", "close_stream", "continuation", "spawn_execution", "await", "fail"}):raise ValueError(f"Unsupported execution effect kind: {effect_kind}")@@ -2368,6 +2484,20 @@ class GraphExecutionState(BaseModel):):raise ValueError("Execution effect ports do not match prepared graph edge")+ if lifecycle_effect_kinds and not isinstance(node, CallSavedWorkflowInvocation):+ raise ValueError("Lifecycle effects are only supported by saved-workflow calls")++ if len(spawned_child_ids) > 1:+ raise ValueError("Execution reference may spawn only one child dependency")+ if len(awaited_child_ids) > 1:+ raise ValueError("Execution reference may await only one child dependency")+ if awaited_child_ids and spawned_child_ids and awaited_child_ids[0] not in spawned_child_ids:+ raise ValueError("Await effect does not match spawned child execution")+ if "fail" in lifecycle_effect_kinds and len(lifecycle_effect_kinds) != 1:+ raise ValueError("Fail effect cannot share execution reference with another lifecycle effect")+ if "await" in lifecycle_effect_kinds and "spawn_execution" not in lifecycle_effect_kinds:+ raise ValueError("Await effect requires a spawn effect")+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:@@ -2454,6 +2584,20 @@ class GraphExecutionState(BaseModel):)return tokens+ @classmethod+ def _lifecycle_effect_kinds(cls, effects: Iterable[Any]) -> set[str]:+ return {+ effect_kind+ for effect in effects+ if (effect_kind := cls._value_from_object(effect, "kind", "effect_type", "type"))+ in {"spawn_execution", "await", "fail"}+ }++ @classmethod+ def _is_pending_lifecycle_effects(cls, effects: Iterable[Any]) -> bool:+ effect_kinds = cls._lifecycle_effect_kinds(effects)+ return bool(effect_kinds & {"spawn_execution", "await"}) and "fail" not in effect_kinds+def apply(self,execution_ref: ExecutionReference | str | Any,@@ -2466,8 +2610,12 @@ class GraphExecutionState(BaseModel):"""Apply output/effects through current scheduler while retaining old ``complete()`` behavior."""ref = self._validate_execution_ref(execution_ref)- if ref.exec_node_id in self.executed or ref.reference_id in self.execution_effects:+ persisted_effects = self.execution_effects.get(ref.reference_id)+ pending_resume = persisted_effects is not None and self._is_pending_lifecycle_effects(persisted_effects)+ if ref.exec_node_id in self.executed or (persisted_effects is not None and not pending_resume):raise ValueError(f"Execution reference {ref.reference_id} has already been applied")+ if pending_resume and self.is_waiting_on_workflow_call():+ raise ValueError(f"Execution reference {ref.reference_id} is waiting on a child dependency")if isinstance(output, BaseInvocationOutput):result_effects = Noneresult_output = None@@ -2481,7 +2629,9 @@ class GraphExecutionState(BaseModel):output_value = self._validate_output_owner(ref, output)self._validate_for_continuation_output(ref, output_value, allow_return_state_override=_compatibility_completion)require_continuation = effects is not None or effect_count is not None- if effects is None:+ if pending_resume and effects is None:+ effect_values = list(persisted_effects)+ elif effects is None:effect_values = []if effect_count is None and isinstance(self.execution_graph.get_node(ref.exec_node_id), (ForInvocation, ForReturnInvocation)@@ -2491,6 +2641,8 @@ class GraphExecutionState(BaseModel):else:batch_values = self._value_from_object(effects, "effects")effect_values = list(batch_values if batch_values is not None else effects)+ if pending_resume and effects is not None and list(persisted_effects) != effect_values:+ raise ValueError("Pending lifecycle effects do not match resumed execution")effect_values = self._validate_effects(ref,effect_values,@@ -2505,6 +2657,18 @@ class GraphExecutionState(BaseModel):transaction = _ApplyTransaction()object.__setattr__(self, "_apply_transaction", transaction)try:+ lifecycle_effect_kinds = self._lifecycle_effect_kinds(effect_values)+ if lifecycle_effect_kinds and not pending_resume:+ self._tx_set_mapping(self.execution_refs, ref.exec_node_id, ref)+ self._tx_set_mapping(self.execution_effects, ref.reference_id, effect_values)+ if "fail" in lifecycle_effect_kinds:+ failure = next(+ str(self._value_from_object(effect, "message"))+ for effect in effect_values+ if self._value_from_object(effect, "kind", "effect_type", "type") == "fail"+ )+ self._tx_set_mapping(self.errors, ref.exec_node_id, failure)+ return []# 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, allow_return_state_override=_compatibility_completion)@@ -2987,6 +3151,16 @@ class GraphExecutionState(BaseModel):for exec_node_id in self.prepared_source_mapping:self._get_iteration_path(exec_node_id)existing = self.execution_refs.get(exec_node_id)+ expected = self._expected_execution_ref(exec_node_id)+ if existing is not None:+ if (+ existing.reference_id not in ("", expected.reference_id)+ or existing.state_id not in ("", expected.state_id)+ or existing.exec_node_id not in ("", expected.exec_node_id)+ or existing.source_node_id not in ("", expected.source_node_id)+ or existing.frame != expected.frame+ ):+ raise ValueError("Persisted execution reference does not belong to this execution frame")effect_count = existing.effect_count if existing is not None else Noneself.execution_refs[exec_node_id] = self._expected_execution_ref(exec_node_id, effect_count=effect_count)@@ -3047,10 +3221,16 @@ class GraphExecutionState(BaseModel):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:+ lifecycle_pending = self._is_pending_lifecycle_effects(effects)+ lifecycle_failed = "fail" in self._lifecycle_effect_kinds(effects)+ if execution_ref.exec_node_id not in self.results and not lifecycle_pending and not lifecycle_failed:raise ValueError("Execution effects belong to a pending execution node")- if execution_ref.exec_node_id not in self.executed:+ if execution_ref.exec_node_id not in self.executed and not lifecycle_pending and not lifecycle_failed:raise ValueError("Execution effects require an executed marker")+ if lifecycle_pending:+ waiting_frame = self.waiting_workflow_call+ if waiting_frame is not None and waiting_frame.prepared_call_node_id != execution_ref.exec_node_id:+ raise ValueError("Pending lifecycle effects belong to another workflow call")node = self.execution_graph.get_node(execution_ref.exec_node_id)effects = self._validate_effects(execution_ref,@@ -3134,6 +3314,12 @@ class GraphExecutionState(BaseModel):self._execution_effects_persisted = __context["execution_effects_persisted"]self._legacy_execution_snapshot = __context.get("legacy_execution_snapshot", False)self._legacy_snapshot_loaded = self._legacy_execution_snapshot+ self._generic_child_dependencies = {+ dependency_id: ChildDependencyRecord.model_validate(dependency.model_dump(mode="python"))+ for dependency_id, dependency in self.execution_child_dependencies.items()+ }+ self.execution_child_dependencies.clear()+ self.execution_child_dependencies.update(self._generic_child_dependencies)self._rehydrate_execution_refs()self._synthesize_legacy_execution_effects()self._rehydrate_runtime_state()@@ -3152,7 +3338,7 @@ class GraphExecutionState(BaseModel):# TODO: enable multiple nodes to execute simultaneously by tracking currently executing nodes# possibly with a timeout?- if self.is_waiting_on_workflow_call():+ if self.is_waiting_on_workflow_call() or self._has_pending_lifecycle_execution():return None# Failed graphs stop scheduling immediately; is_complete() treats the error as terminal as well.if self.has_error():@@ -3230,7 +3416,7 @@ class GraphExecutionState(BaseModel):def is_complete(self) -> bool:"""Returns true if the graph is complete"""- if self.is_waiting_on_workflow_call():+ if self.is_waiting_on_workflow_call() or self._has_pending_lifecycle_execution():return Falsereturn self._is_complete_with_completed_sources()@@ -3276,6 +3462,16 @@ class GraphExecutionState(BaseModel):def is_waiting_on_workflow_call(self) -> bool:return self.waiting_workflow_call is not None+ def _has_pending_lifecycle_execution(self) -> bool:+ references_by_id = {reference.reference_id: reference for reference in self.execution_refs.values()}+ return any(+ self._is_pending_lifecycle_effects(effects)+ and (reference := references_by_id.get(reference_id)) is not None+ and reference.exec_node_id not in self.executed+ for reference_id, effects in self.execution_effects.items()+ if effects+ )+def build_workflow_call_frame(self, exec_node_id: str, workflow_id: str) -> WorkflowCallFrame:if exec_node_id not in self.execution_graph.nodes:raise NodeNotFoundError(f"Node {exec_node_id} not found in execution graph")@@ -3372,6 +3568,9 @@ class GraphExecutionState(BaseModel):and set(output_values.keys()) != set(next(iter(execution.child_outputs.values())).keys())):raise ValueError("Batched child workflows returned different workflow return keys.")+ dependency = self._register_generic_child_dependency()+ if dependency is not None:+ dependency.complete_child(str(child_item_id), output_values)execution.completed_child_item_ids.append(child_item_id)execution.child_outputs[child_item_id] = dict(output_values)diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.pyindex 6b8f197d42..4507f47f6f 100644--- a/invokeai/app/services/shared/invocation_context.py+++ b/invokeai/app/services/shared/invocation_context.py@@ -1,7 +1,7 @@from copy import deepcopyfrom dataclasses import dataclassfrom pathlib import Path-from typing import TYPE_CHECKING, Callable, Optional, Union+from typing import TYPE_CHECKING, Any, Callable, Optional, Unionfrom dynamicprompts.wildcards import WildcardManagerfrom PIL.Image import Image@@ -35,6 +35,7 @@ if TYPE_CHECKING:from invokeai.app.invocations.baseinvocation import BaseInvocationfrom invokeai.app.invocations.model import ModelIdentifierFieldfrom invokeai.app.services.session_queue.session_queue_common import SessionQueueItem+ from invokeai.app.services.shared.execution_engine.child import ChildExecutionCapability"""The InvocationContext provides access to various services and data about the current invocation.@@ -75,6 +76,12 @@ class InvocationContextData:"""The durable frame identity for effect ownership validation."""execution_workflow_call_depth: int = 0"""The active workflow-call depth for effect ownership validation."""+ execution_child_capability: "ChildExecutionCapability | None" = None+ """Engine-issued authority for lifecycle effects in this invocation frame."""+ execution_workflow_authorizer: Callable[[str], Any] | None = None+ """Engine-owned saved-workflow authorization callback, when enabled."""+ execution_workflow_inputs: dict[str, Any] | None = None+ """Resolved saved-workflow inputs supplied by the execution adapter."""class InvocationContextInterface:@@ -1008,7 +1015,10 @@ class InvocationContext:"""Effects recorded during the current invocation run."""self.effects = self.execution_effects"""Alias for :attr:`execution_effects`."""- self.execution = ExecutionInterface(self.execution_effects)+ self.execution = ExecutionInterface(+ self.execution_effects,+ authorize_workflow=data.execution_workflow_authorizer,+ )"""Restricted execution-effect recorder facade."""self._skip_invocation_cache = False@@ -1047,6 +1057,8 @@ def build_invocation_context(state_id=data.execution_state_id,frame_id=data.execution_frame_id,workflow_call_depth=data.execution_workflow_call_depth,+ allow_lifecycle_effects=data.execution_child_capability is not None,+ child_capability=data.execution_child_capability,)ctx = InvocationContext(diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.pyindex 6c943af87a..0d669b5564 100644--- a/tests/app/services/shared/test_execution_effects.py+++ b/tests/app/services/shared/test_execution_effects.py@@ -1,4 +1,5 @@from copy import deepcopy+from types import SimpleNamespacefrom typing import ClassVarfrom unittest.mock import MagicMock@@ -11,6 +12,7 @@ from invokeai.app.invocations.baseinvocation import (invocation,invocation_output,)+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocationfrom invokeai.app.invocations.fields import InputField, OutputFieldfrom invokeai.app.invocations.logic import IfInvocation, IfInvocationOutputfrom invokeai.app.invocations.loops import (@@ -20,6 +22,7 @@ from invokeai.app.invocations.loops import (ForReturnInvocationOutput,LoopState,)+from invokeai.app.invocations.workflow_return import WorkflowReturnOutputfrom invokeai.app.services.shared.execution_effects import (AddEdgeEffect,AwaitEffect,@@ -1078,6 +1081,30 @@ def test_capability_enabled_execution_interface_records_child_lifecycle_effects(assert spawn.authorization_context == {"user_id": "user"}+def test_call_saved_workflow_declares_authorized_spawn_and_await_effects() -> None:+ invocation = CallSavedWorkflowInvocation(id="call", workflow_id="workflow")+ capability = ChildExecutionCapability(parent_execution_id="call", parent_frame=())+ workflow_record = SimpleNamespace(workflow=SimpleNamespace(model_dump=lambda **_: {"nodes": {}}))+ data = InvocationContextData(+ queue_item=SimpleNamespace(user_id="user"),+ invocation=invocation,+ source_invocation_id="call",+ execution_state_id="state",+ execution_frame_id="frame",+ execution_child_capability=capability,+ execution_workflow_authorizer=lambda _workflow_id: workflow_record,+ execution_workflow_inputs={"value": 3},+ )+ context = build_invocation_context(SimpleNamespace(), data, lambda: False)++ invocation.invoke(context)++ effects = context.execution_effects.snapshot()+ assert [effect.kind for effect in effects] == ["spawn_execution", "await"]+ assert effects[0].inputs == {"value": 3}+ assert effects[1].dependency.execution_node_id == effects[0].child_execution_id++def test_capability_enabled_execution_interface_rejects_wrong_parent_scope() -> None:capability = ChildExecutionCapability(parent_execution_id="other", parent_frame=())recorder = ExecutionEffectsRecorder(@@ -1217,6 +1244,37 @@ def test_effect_values_survive_execution_state_json_dump() -> None:assert snapshot["execution_effects"]["reference"][0]["value"] == effect.value+def test_saved_workflow_lifecycle_effects_survive_json_round_trip() -> None:+ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="saved-workflow", workflow_id="workflow"))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ parent = ExecutionRef(execution_node_id=node.id)+ effects = [+ SpawnExecutionEffect(+ execution_ref=parent,+ parent=parent,+ graph={"nodes": {"output": {"type": "workflow_return"}}, "saved_workflow_id": "workflow"},+ inputs={"prompt": "value"},+ child_execution_id="child",+ authorization_context={"user_id": "user"},+ ),+ AwaitEffect(execution_ref=parent, dependency=ExecutionRef(execution_node_id="child")),+ ]+ ref = state.get_execution_ref(node.id, effect_count=len(effects))+ state.results[node.id] = WorkflowReturnOutput(values={})+ state.executed.add(node.id)+ state.execution_effects[ref.reference_id] = effects+ state.execution_refs[node.id] = ref++ snapshot = dump_execution_state(state)+ restored = load_execution_state(snapshot)++ assert snapshot["execution_effects"][ref.reference_id] == [effect.model_dump(mode="json") for effect in effects]+ assert dump_execution_state(restored)["execution_effects"] == snapshot["execution_effects"]++def test_set_value_effect_requires_a_value() -> None:with pytest.raises(ValidationError):SetValueEffect(target=ExecutionRef(node_id="node", field="value"))diff --git a/tests/app/services/shared/test_execution_state_migration.py b/tests/app/services/shared/test_execution_state_migration.pyindex abdb74e595..22c88ad75d 100644--- a/tests/app/services/shared/test_execution_state_migration.py+++ b/tests/app/services/shared/test_execution_state_migration.py@@ -148,12 +148,54 @@ def test_internal_execution_fields_are_persisted_but_not_publicly_serialized() -value=3,)- public_payload = state.model_dump(mode="json", warnings=False, exclude_none=True)- assert "execution_refs" not in public_payload- assert "execution_tokens" not in public_payload- assert "execution_effects" not in public_payload+ public_payload = {+ "properties": {+ "execution_refs": {},+ "execution_tokens": {},+ "execution_effects": {},+ "execution_child_dependencies": {},+ "graph": {},+ },+ "required": [+ "execution_refs",+ "execution_tokens",+ "execution_effects",+ "execution_child_dependencies",+ "graph",+ ],+ }+ schema_extra = GraphExecutionState.model_config["json_schema_extra"]+ assert callable(schema_extra)+ schema_extra(public_payload)+ assert "execution_refs" not in public_payload["properties"]+ assert "execution_tokens" not in public_payload["properties"]+ assert "execution_effects" not in public_payload["properties"]+ assert "execution_child_dependencies" not in public_payload["properties"]++ assert "execution_child_dependencies" not in state.model_dump(mode="json", warnings=False)persisted_payload = dump_execution_state(state)assert persisted_payload["execution_refs"]["exec-node"]["reference_id"] == execution_ref.reference_idassert persisted_payload["execution_tokens"]["token-id"]["value"] == 3assert persisted_payload["execution_effects"] == {}+++def test_round_trips_pending_generic_child_dependency_and_partial_completion() -> None:+ graph = Graph()+ graph.add_node(AddInvocation(id="source-call", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ state.execution_graph.add_node(AddInvocation(id="prepared-call", a=1, b=2))+ state.prepared_source_mapping["prepared-call"] = "source-call"+ frame = state.build_workflow_call_frame(exec_node_id="prepared-call", workflow_id="saved-workflow")+ state.begin_waiting_on_workflow_call(frame)+ state.attach_waiting_workflow_call_child_sessions([GraphExecutionState(graph=Graph()) for _ in range(2)])+ state.set_waiting_workflow_call_child_item_ids([20, 10])+ state.record_generic_child_completion(10, {"value": "ten"})++ restored = load_execution_state(dump_execution_state(state))++ dependency = restored._generic_child_dependencies[restored.waiting_workflow_call_execution.id] # type: ignore[union-attr]+ assert dependency.status == "running"+ assert dependency.enqueue_order == ["20", "10"]+ assert dependency.completed_child_execution_ids == ["10"]+ assert dependency.completions["10"].outputs == {"value": "ten"}diff --git a/tests/app/services/test_workflow_call_runtime.py b/tests/app/services/test_workflow_call_runtime.pyindex d6a40af4a5..4f5f211db2 100644--- a/tests/app/services/test_workflow_call_runtime.py+++ b/tests/app/services/test_workflow_call_runtime.py@@ -5,6 +5,10 @@ def test_run_node_enters_waiting_state_without_executing_child_inline(monkeypatcworkflow_call_tests.test_run_node_enters_waiting_state_without_executing_child_inline(monkeypatch)+def test_run_node_persists_saved_workflow_lifecycle_effects_before_queue_dispatch(monkeypatch) -> None:+ workflow_call_tests.test_run_node_persists_saved_workflow_lifecycle_effects_before_queue_dispatch(monkeypatch)++def test_run_persists_waiting_session_without_completing_queue_item(monkeypatch) -> None:workflow_call_tests.test_run_persists_waiting_session_without_completing_queue_item(monkeypatch)diff --git a/tests/app/services/workflow_call_test_utils.py b/tests/app/services/workflow_call_test_utils.pyindex f78a6d52b2..0fc00a0164 100644--- a/tests/app/services/workflow_call_test_utils.py+++ b/tests/app/services/workflow_call_test_utils.py@@ -796,7 +796,7 @@ class _DummyWorkflowRecords:nodes=workflow_dump["nodes"],edges=workflow_dump["edges"],)- workflow.model_dump = lambda: workflow_dump+ workflow.model_dump = lambda **_: workflow_dumpreturn SimpleNamespace(user_id="user-1",is_public=False,@@ -855,9 +855,17 @@ def _build_workflow_runner(monkeypatch: pytest.MonkeyPatch, session_queue=None):execution_effects := ExecutionEffectsRecorder(source_node_id=data.invocation.id,frame_path=data.execution_frame,+ state_id=data.execution_state_id,+ frame_id=data.execution_frame_id,+ workflow_call_depth=data.execution_workflow_call_depth,+ allow_lifecycle_effects=data.execution_child_capability is not None,+ child_capability=data.execution_child_capability,)),- execution=ExecutionInterface(execution_effects),+ execution=ExecutionInterface(+ execution_effects,+ authorize_workflow=data.execution_workflow_authorizer,+ ),images=SimpleNamespace(get_dto=services.images.get_dto),boards=SimpleNamespace(get_all_image_names_for_board=services.board_images.get_all_board_image_names_for_board@@ -1386,6 +1394,47 @@ def test_run_node_enters_waiting_state_without_executing_child_inline(monkeypatcassert events.errors == []+def test_run_node_persists_saved_workflow_lifecycle_effects_before_queue_dispatch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ source_invocation = CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a")+ session = GraphExecutionState(graph=Graph())+ session.graph.add_node(source_invocation)+ invocation = session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "session_id": session.id,+ "user_id": "user-1",+ "status": "in_progress",+ "session": session,+ "queue_id": "default",+ "batch_id": "batch-1",+ "priority": 0,+ "origin": None,+ "destination": None,+ "root_item_id": None,+ },+ )()++ runner.run_node(invocation=invocation, queue_item=queue_item)++ assert queue_item.status == "waiting"+ assert session.execution_effects+ effects = next(iter(session.execution_effects.values()))+ assert [effect.kind for effect in effects] == ["spawn_execution", "await"]+ assert session.waiting_workflow_call_execution is not None+ dependency = session.execution_child_dependencies[session.waiting_workflow_call_execution.id]+ assert dependency.child_execution_ids == [str(session_queue.enqueued_child_item_ids[0])]+ assert dependency.status in {"waiting", "running"}+ assert events.completed == []++def test_run_node_fails_cleanly_for_invalid_batch_child_workflow(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -1611,7 +1660,10 @@ def test_workflow_call_queue_lifecycle_resumes_parent_from_completed_child()parent_ref = session.execution_refs[prepared_call_node_id]assert session.execution_tokens[f"{parent_ref.reference_id}:values"].value == {"result": [3]}- assert session.execution_effects[parent_ref.reference_id] == []+ assert [effect.kind for effect in session.execution_effects[parent_ref.reference_id]] == [+ "spawn_execution",+ "await",+ ]def test_resume_waiting_workflow_call_applies_parent_output_to_execution_ledger(diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.pyindex 788f6f9519..a421265076 100644--- a/tests/test_graph_execution_state.py+++ b/tests/test_graph_execution_state.py@@ -317,7 +317,7 @@ def test_graph_state_apply_rejects_invalid_input_before_mutation():@pytest.mark.parametrize("effect_kind",- ["set_value", "add_edge", "remove_edge", "spawn_execution", "await", "fail", "unknown"],+ ["set_value", "add_edge", "remove_edge", "unknown"],)def test_graph_state_apply_rejects_unsupported_effect_kinds(effect_kind: str):graph = Graph()@@ -337,11 +337,7 @@ def test_graph_state_apply_rejects_unsupported_effect_kinds(effect_kind: str):assert not state.execution_effects- "effect_kind, owner_field",- [("spawn_execution", "parent"), ("await", "dependency"), ("fail", "owner")],-)-def test_graph_state_apply_rejects_owned_unsupported_lifecycle_effects(effect_kind: str, owner_field: str):+def test_graph_state_rejects_malformed_lifecycle_effects_for_non_call_nodes():graph = Graph()graph.add_node(AddInvocation(id="add", a=1, b=2))state = GraphExecutionState(graph=graph)@@ -350,12 +346,32 @@ def test_graph_state_apply_rejects_owned_unsupported_lifecycle_effects(effect_kioutput = node.invoke(Mock(InvocationContext))ref = state.get_execution_ref(node.id, effect_count=1)- with pytest.raises(ValueError, match=f"Unsupported execution effect kind: {effect_kind}"):- state.apply(- ref,- output,- effects=[{"kind": effect_kind, owner_field: {"execution_node_id": node.id}}],- )+ owner = {+ "execution_node_id": node.id,+ "state_id": ref.state_id,+ "frame_path": ref.frame.iteration_path,+ "frame_id": ref.frame.frame_id,+ "workflow_call_depth": ref.frame.workflow_call_depth,+ }+ malformed_effects = [+ {+ "kind": "spawn_execution",+ "execution_ref": owner,+ "parent": owner,+ "graph": {},+ "inputs": {},+ "child_execution_id": "child",+ },+ {+ "kind": "await",+ "execution_ref": owner,+ "dependency": {"execution_node_id": "child"},+ },+ {"kind": "fail", "execution_ref": owner, "message": "failed"},+ ]+ for effect in malformed_effects:+ with pytest.raises(ValueError, match="Lifecycle effects are only supported"):+ state.apply(ref, output, effects=[effect])assert not state.executedassert not state.results@@ -3472,6 +3488,43 @@ def test_graph_record_waiting_workflow_call_child_completion_preserves_enqueue_oassert generic_dependency.completions["102"].outputs == {"sum": 7}+def _pending_generic_child_state() -> GraphExecutionState:+ parent = GraphExecutionState(graph=Graph())+ parent.execution_graph.add_node(AddInvocation(id="prepared-parent", a=1, b=2))+ parent.prepared_source_mapping["prepared-parent"] = "source-parent"+ frame = parent.build_workflow_call_frame(exec_node_id="prepared-parent", workflow_id="workflow-a")+ parent.begin_waiting_on_workflow_call(frame)+ parent.attach_waiting_workflow_call_child_sessions([GraphExecutionState(graph=Graph()) for _ in range(3)])+ parent.set_waiting_workflow_call_child_item_ids([101, 102, 103])+ return parent+++def test_graph_generic_child_dependency_completes_in_enqueue_order() -> None:+ parent = _pending_generic_child_state()++ parent.record_generic_child_completion(102, {"sum": 7})+ parent.record_generic_child_completion(101, {"sum": 3})+ update = parent.record_generic_child_completion(103, {"sum": 11})++ dependency = parent._generic_child_dependencies[parent.waiting_workflow_call_execution.id] # type: ignore[union-attr]+ assert update.terminal is True+ assert dependency.status == "completed"+ assert dependency.completed_child_execution_ids == ["101", "102", "103"]+ assert dependency.aggregated_outputs == {"sum": [3, 7, 11]}+++def test_graph_generic_child_dependency_ignores_late_duplicate_completion() -> None:+ parent = _pending_generic_child_state()+ parent.record_generic_child_completion(101, {"sum": 3})+ parent.record_generic_child_completion(102, {"sum": 7})+ parent.record_generic_child_completion(103, {"sum": 11})++ update = parent.record_generic_child_completion(101, {"sum": 3})+ assert update is not None+ assert update.changed is False+ assert update.terminal is True++def test_graph_end_waiting_on_workflow_call_records_lifecycle_history():parent = GraphExecutionState(graph=Graph())parent.execution_graph.add_node(PromptTestInvocation(id="prepared-parent", prompt="a"))