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): complete final cleanup
JPPhoto9ae344a55625
diff --git a/docs/src/content/docs/contributing/call-saved-workflow.md b/docs/src/content/docs/contributing/call-saved-workflow.mdindex 35458174d6..5624c7005b 100644--- a/docs/src/content/docs/contributing/call-saved-workflow.md+++ b/docs/src/content/docs/contributing/call-saved-workflow.md@@ -2,57 +2,53 @@title: Call Saved Workflow Architecture----## Goal+## Callable Workflow Contract-`CallSavedWorkflowInvocation` should become an engine-native workflow call boundary, not a frontend-only dynamic node-and not a compile-time graph inliner.+`CallSavedWorkflowInvocation` is an engine-native workflow call boundary, not a frontend-only dynamic node and not a+compile-time graph inliner.-The long-term feature goal is:+The callable-workflow contract is:- A parent workflow can call a saved workflow selected by ID.- The call node redraws in the editor based on the selected workflow's exposed form fields.- Parent values and inbound connections bind to those exposed fields as call arguments.- Execution suspends at the call node, runs the selected workflow as a dependent workflow execution, captures explicitreturn values, and then resumes the parent workflow.-- The architecture must work for Invoke frontend graphs and for externally submitted graphs that use the same node type.+- 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. 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+This document describes the callable-workflow architecture and execution contract. Saved-workflow calls use a dedicated+queue boundary for durable rows and queue transitions, while invocation and graph state use the lifecycleeffect/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.-Internal execution references, tokens, effects, frames, and scheduler records are persistence-only implementation-metadata. `dump_execution_state()` retains `execution_refs`, `execution_tokens`, `execution_effects`, and-`execution_child_dependencies`, including attached child states. Ordinary model serialization and public schemas exclude-these four internal ledgers. 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 callable node, saved-workflow, and queue interaction contract is stable. Internal execution references, tokens,+effects, frames, and scheduler records are persistence-only implementation metadata. `dump_execution_state()` retains+`execution_refs`, `execution_tokens`, `execution_effects`, and `execution_child_dependencies`, including attached child+states. Ordinary model serialization and public schemas exclude these four internal ledgers. Existing fields,+requiredness, statuses, events, and client behavior remain compatible. Frontend application behavior is outside this+backend architecture. No code under `invokeai/frontend/...`, including generated `openapi.json` or `schema.ts`, is part+of this execution behavior; the existing frontend/backend external interface is stable.-The internal generic boundary is implemented in-`invokeai.app.services.shared.execution_engine`. It provides frame-scoped-gates, ordered streams, continuations, and capability-bound child dependency-records. These records are used as adapters around the existing queue and-materialization paths; they do not add frontend handles, queue statuses, event-payloads, or author-time graph fields.+The internal generic boundary is implemented in `invokeai.app.services.shared.execution_engine`. It provides+frame-scoped gates, ordered streams, continuations, and capability-bound child dependency records. These records are+used as adapters around the existing queue and materialization paths; they do not add frontend handles, queue statuses,+event payloads, or author-time graph fields.-## Implementation Priority+## Design PrinciplesFavor the architecturally correct design over the fastest implementation path.-The work may still proceed incrementally, but each increment should satisfy all of the following:+Changes to this area should satisfy all of the following:- testable in isolation- compatible with the long-term architecture described here- non-breaking to existing code and existing workflow execution behavior-Speed is not the primary goal for this phase. The primary goal is to move toward the durable design without introducing-throwaway execution semantics that would need to be unwound later.+The durable design is preferred over throwaway execution semantics.-## Current State+## Current Behavior-Implemented already in the branch:+The callable-workflow feature provides:- A real invocation exists: `call_saved_workflow`.- A real return node exists: `workflow_return`.@@ -68,7 +64,7 @@ Implemented already in the branch:- Incompatible or no-longer-exposed inbound edges are removed in the editor.- Backend validation exists for `workflow_id` existence and access rights.-The branch also contains the additive execution-effects seam:+The runtime uses an additive execution-effects seam:- the runner invokes `invoke_internal_with_effects()` and applies its result through `GraphExecutionState.apply()`;- stable execution references, frames, output tokens, and accepted effects are persisted with the runtime state;@@ -78,7 +74,7 @@ The branch also contains the additive execution-effects seam:- saved workflow calls continue through `WorkflowCallCoordinator` and `WorkflowCallQueueLifecycle`, with a genericchild dependency record validating their relationship and aggregation.-Implemented runtime scaffolding:+Runtime state:- `GraphExecutionState` now persists workflow-call runtime state:- `workflow_call_stack`@@ -133,19 +129,21 @@ Implemented runtime scaffolding:- `root_item_id`- `workflow_call_depth`- child workflow executions are now inserted as their own pending queue rows using those columns-- Child queue rows and the parent's complete waiting-session projection are published in one durable queue- transaction. Concurrent child completions update the latest parent session transactionally, so a sibling cannot- overwrite another sibling's completion.+- Child queue rows and the parent's complete waiting-session projection are published in one durable queue transaction.+ Concurrent child completions update the latest parent session transactionally, so a sibling cannot overwrite another+ sibling's completion.- Parent queue items now enter a real `waiting` status while suspended on a child workflow execution.- `_on_after_run_session()` no longer completes queue items whose sessions are incomplete but waiting.- Dynamic call arguments now execute end-to-end in the current runner path:- - literal dynamic values are serialized into a hidden `workflow_inputs` payload on the parent node at graph-build time+ - literal dynamic values are serialized into a hidden `workflow_inputs` payload on the parent node at graph-build+ time- stale hidden `workflow_inputs` values from recalled graphs are ignored unless a matching current dynamic fieldexists- existing dynamic input values are preserved across refresh only while the exposed field type remains compatible; ifthe selected child workflow changes the exposed field type at the same node/field path, the caller input resets tothe child workflow's current initial value- - connected dynamic values are accepted as special call-boundary edges and are resolved from parent results at runtime+ - connected dynamic values are accepted as special call-boundary edges and are resolved from parent results at+ runtime- both are validated against the child workflow's exposed form interface before being applied to the child graph- Queue lifecycle semantics now exist for workflow-call chains:- parent queue items are suspended in `waiting` while a child queue row runs@@ -165,20 +163,20 @@ Implemented runtime scaffolding:- child queue rows keep `Cancel`- child queue rows hide `Retry`- child queue-row creation is now fail-clean:- - if call-boundary setup fails after some child rows have already been inserted, those child rows are deleted before- the parent invocation is failed+ - if call-boundary setup fails after some child rows have already been inserted, those child rows are deleted+ before the parent invocation is failed- child queue-row fan-out is bounded by remaining queue capacity, not just the global queue-size setting:- a workflow call that would exceed the remaining pending capacity now fails instead of silently truncating orover-enqueuing child rows- child insertion rechecks pending capacity in the same database transaction as the insert-Implemented conversion helper:+Workflow conversion:- `workflow_graph_builder.py` converts saved workflow JSON into an executable backend `Graph`.- It currently supports the invocation-node subset needed for this feature.- It flattens connector nodes and omits explicit destination field values when a connection exists, matching frontendgraph-build semantics.-- It now serves as the first explicit callable-workflow compatibility gate:+- It enforces the callable-workflow boundary:- the selected workflow must contain exactly one `workflow_return` node- connected batch child inputs produced by ordinary non-generator upstream nodes still fail early with a clearunsupported-feature error@@ -197,7 +195,7 @@ Implemented conversion helper:- workflow library list items now surface an explicit unsupported badge and localized reason without blocking normalworkflow viewing or editing-What is still not implemented:+Current callable-workflow limitations:- connected batch child inputs whose batch values are produced by ordinary non-generator upstream nodes are still notsupported and must fail with a clear domain error@@ -210,18 +208,12 @@ What is still not implemented:identity, ordered all-of aggregation, resource limits, and idempotent child terminal events before the existing queueadapter resumes, fails, or cancels the parent-Conclusion:+The editor contract, parent call boundary, child execution, argument forwarding, explicit return capture, suspended+parent status, queue-visible child rows, and upward failure cascade are all handled by the current runtime.-- the editor contract is largely in place-- the parent-side runtime call boundary is in place-- child execution, argument forwarding, explicit child return capture, suspended parent status, queue-visible child- rows, and upward failure cascade now work-- the remaining major runtime work is to harden and generalize the parent/child scheduler model rather than prove the- basic call boundary+## Architecture-## Architectural Direction--Use the architecture that is more likely to be kept long-term:+The implementation uses the following architecture:- `call_saved_workflow` is a call boundary.- The parent graph does not inline the full child workflow into itself at queue time.@@ -230,7 +222,7 @@ Use the architecture that is more likely to be kept long-term:- The child workflow returns explicit outputs to the parent.- The parent resumes once the child returns successfully.-This is preferred over full graph expansion because it:+This keeps execution at the call boundary instead of expanding the full child graph because it:- avoids execution-graph blowup- preserves workflow boundaries@@ -238,9 +230,9 @@ This is preferred over full graph expansion because it:- supports explicit return values- keeps externally submitted graphs viable as long as they use the same node type and contract-## Non-Goals For The Next Phase+## Current Limitations-These should not be the first implementation target:+The current implementation does not provide:- full inline graph expansion of called workflows- unlimited nested workflow call support@@ -278,8 +270,8 @@ Each dynamic input must have:- a default value if defined by the child workflow- a user-facing label and description when available-Current fast-path identity is based on child `nodeId + fieldName`. That is acceptable short-term in the editor, but a-longer-term stable interface ID would be better if child workflows are frequently duplicated or refactored.+Current fast-path identity is based on child `nodeId + fieldName`. A stable interface ID may be useful if child+workflows are frequently duplicated.### 3. Input Binding At Runtime@@ -296,14 +288,14 @@ Argument values may come from:- parent literal field values- resolved inbound connections into the call node's dynamic inputs-For batch-aware child workflows, the parent call boundary should still pass normal exposed form inputs. Batching should-emerge from the child workflow's own internal batch nodes or generators, not from a separate caller-side batch protocol.+For batch-aware child workflows, the parent call boundary passes normal exposed form inputs. Batching emerges from the+child workflow's own internal batch nodes or generators, not from a separate caller-side batch protocol.### 4. Child Workflow ExecutionThe child workflow runs as its own dependent execution context, not as an inlined copy of the parent graph.-Desired semantics:+Execution semantics:- parent execution pauses at the call node- child execution runs with inherited context where appropriate@@ -315,13 +307,12 @@ durable queue metadata, and queue-visible child rows.Current limitation:-- the temporary `workflow_graph_builder.py` path still reconstructs only the ordinary invocation subset of child- workflows+- the `workflow_graph_builder.py` path currently reconstructs only the ordinary invocation subset of child workflows- direct batch-special child workflows now bypass that path and use queue batch expansion instead- generator-backed batch child workflows now bypass that path too when the batch is fed directly by a supportedgenerator node-- connected batch child inputs produced by ordinary non-generator upstream nodes are still not supported and should fail- early with a clear unsupported-feature error+- connected batch child inputs produced by ordinary non-generator upstream nodes are still not supported and fail early+ with a clear unsupported-feature error- the current queue-visible child execution path still relies on `WorkflowCallCoordinator` and`WorkflowCallQueueLifecycle` for durable row creation and parent transitions; generic lifecycle effects and`ChildDependencyRecord` supply the invocation intent, identity, ordered aggregation, idempotency, and terminal@@ -351,8 +342,8 @@ validation and aggregation seam; it does not add queue columns, statuses, eventsmust receive only the retry item ids for their own roots, while admins can still observe the full retried set- workflow live-update sockets join workflow event rooms in both authenticated multiuser mode and unauthenticatedsingle-user mode; the frontend relies on those events to invalidate workflow library data and clear deleted saved- workflow selections; in single-user mode, workflow CRUD events emit only to the admin room to avoid duplicate delivery- to sockets that are also joined to `user:system`+ workflow selections; in single-user mode, workflow CRUD events emit only to the admin room to avoid duplicate+ delivery to sockets that are also joined to `user:system`- a public-to-private transition emits a schema-defined `workflow_access_revoked` event to shared-workflow subscribers;non-owner, non-admin clients clear references to that workflow while owners and admins retain access- the saved-workflow node picker queries owned/default workflows and public shared workflows separately, merges them by@@ -393,7 +384,8 @@ Current semantics:- the workflow call creates one child queue row per expanded batch session- supported generator value shapes are resolved into concrete batch items before queue batch expansion- declared generator counts are rejected before resolution when they exceed remaining child capacity-- cartesian expansion size is computed arithmetically before session generation rather than by materializing the product+- cartesian expansion size is computed arithmetically before session generation rather than by materializing the+ product- batch outputs may feed a named `workflow_return_value.value` directly; each expanded child returns one value for thatkey- parent resume waits for all child rows tied to that workflow call@@ -498,8 +490,8 @@ Retry behavior:- retry is root-oriented- child queue rows should not be directly retried from the UI-- backend retry of a child id should normalize to the root workflow call chain rather than create an isolated child-only- rerun+- backend retry of a child id should normalize to the root workflow call chain rather than create an isolated+ child-only rerun### 5. Return Values@@ -534,8 +526,8 @@ Batch return aggregation:- when a called workflow expands into multiple child queue rows, each child row produces its own named return map- the parent aggregates those child maps as `dict[str, list[Any]]`-- each key maps to child values in child enqueue order, preserving positional correspondence with batch inputs even when- child executions complete out of order+- each key maps to child values in child enqueue order, preserving positional correspondence with batch inputs even+ when child executions complete out of order- duplicate keys within a single child return map are still invalid; repeated keys across batch children are the normalaggregation path@@ -544,9 +536,9 @@ Batch return aggregation:If child execution fails:- the call node fails-- the parent workflow fails unless a later design adds explicit error-handling semantics+- the parent workflow fails-For the first implementation, failure propagation should be simple and strict.+Failure propagation is simple and strict.### 7. Access Control@@ -558,9 +550,9 @@ This matters even if the parent workflow was authored in a context where the chi### 8. Recursion And Nesting-Nested and recursive `call_saved_workflow` execution should be allowed, but bounded.+Nested and recursive `call_saved_workflow` execution is allowed, but bounded.-Initial implementation should enforce:+The runtime enforces:- nested workflow calls are allowed- recursive workflow calls are allowed@@ -570,16 +562,15 @@ Initial implementation should enforce:This allows legitimate recursive or conditionally terminating workflow structures while still preventing unbounded callgrowth.-## Where The Runtime Work Belongs+## Runtime Ownership-The goal is to support externally submitted graphs, not only frontend-authored graphs. Therefore the authoritative-execution logic must live in Python.+Externally submitted graphs and frontend-authored graphs use the same Python execution path. The backend owns the+authoritative execution logic.-Recommended high-level design:+The runtime design is:- a backend `GraphExpander` or broader graph-preparation service may still exist as an abstraction point-- but for this feature, the preferred long-term runtime model is not full graph expansion-- instead, the runtime needs a call-execution mechanism in the Python execution stack+- the runtime uses a call-execution mechanism in the Python execution stack rather than full graph expansionRelevant existing path:@@ -593,14 +584,14 @@ Current insertion points already used:- `DefaultSessionRunner.run_node()` supplies the call capability and inputs, invokes the node through the effect-awarepath, persists its pending lifecycle effects through `GraphExecutionState.apply()`, then dispatches the queue adapter- `GraphExecutionState` stores the waiting/call-stack state and attached child session-- `WorkflowCallCoordinator` currently establishes the call boundary and enqueues child workflow executions as real queue- rows+- `WorkflowCallCoordinator` currently establishes the call boundary and enqueues child workflow executions as real+ queue rows- `WorkflowCallQueueLifecycle` currently resumes or fails parents when those child rows complete- child queue items already carry stable parent/child identifiers in both runtime objects and durable queue columns-Next runtime work still needed:+Queue lifecycle boundary:-- keep `WorkflowCallQueueLifecycle` as the bounded workflow-call lifecycle component for this refactor+- `WorkflowCallQueueLifecycle` remains the bounded workflow-call lifecycle component- 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@@ -635,7 +626,7 @@ The dedicated child-workflow return nodes are implemented. Responsibilities:- guarantee that only one such node exists per workflow- behave as a normal node in the editor, with singularity enforced by both frontend and Python validation/runtime code-This should remain the canonical reusable return mechanism for any future subworkflow call behavior.+This is the canonical reusable return mechanism for subworkflow calls.### Execution Relationship Tracking@@ -648,8 +639,7 @@ Session/runtime state records:### Workflow Return Value Flow-The workflow return value should not be persisted back into the saved workflow record and should not be derived from-frontend state.+The workflow return value is not persisted back into the saved workflow record and is not derived from frontend state.The intended runtime flow is:@@ -663,17 +653,13 @@ The intended runtime flow is:1. The parent `call_saved_workflow` node is completed with that returned named value map.1. The parent graph resumes.-## Named Return Implementation Status--Named returns are implemented for backend invocation behavior, caller-side extraction, runtime propagation, and batch-aggregation. Remaining work is limited to incremental frontend UX cleanup and any future expansion of supported batch-shapes.+## Named Return Contract-### Stage 1: Backend Return Contract+Named returns cover backend invocation behavior, caller-side extraction, runtime propagation, and batch aggregation.-Status: implemented in backend invocation tests.+### Backend Return Contract-Goal:+Current behavior:- establish the named return data model and invocation primitives@@ -681,22 +667,21 @@ Contract:- `WorkflowReturnValueField` stores one `key: str` and one `value: Any`- `workflow_return_value` creates a single `WorkflowReturnValueField` from a key and connected value-- `workflow_return` accepts either one `WorkflowReturnValueField` member or a list of `WorkflowReturnValueField` members+- `workflow_return` accepts either one `WorkflowReturnValueField` member or a list of `WorkflowReturnValueField`+ members- `WorkflowReturnOutput` exposes `values: dict[str, Any]`- duplicate keys in one non-batch `workflow_return` execution are invalid and must fail clearly-Tests first:+Validation:- `workflow_return_value` emits the requested key/value pair- `workflow_return` emits a named value map from one or more return members- duplicate keys in one `workflow_return` execution are rejected- empty returns are valid only if that remains an intentional callable-workflow contract-### Stage 2: Caller-Side Extraction Primitive--Status: implemented in backend invocation tests.+### Caller-Side Extraction Primitive-Goal:+Current behavior:- let the calling workflow extract a named return value without relying on collection position@@ -704,19 +689,17 @@ Contract:- `workflow_return_get` accepts the named return map and a key- `workflow_return_get` outputs the selected value as `Any`-- missing keys fail clearly unless a later version intentionally adds default-value support+- missing keys fail clearly-Tests first:+Validation:- extracting an existing key returns the stored value- extracting a missing key fails with a useful message- extracted `Any` values can feed typed downstream nodes through the existing connection compatibility rules-### Stage 3: Runtime Propagation+### Runtime Propagation-Status: implemented in backend runtime tests.--Goal:+Current behavior:- carry named return maps through queue-visible child execution and parent resume@@ -727,17 +710,15 @@ Contract:- failed child execution behavior is unchanged- cancel/retry lifecycle behavior is unchanged-Tests first:+Validation:- a called workflow returning `{image: image_value}` completes the parent `call_saved_workflow` output with that key- a caller-side extraction node can consume that output after parent resume- missing or invalid `workflow_return` nodes still fail with the existing clear errors-### Stage 4: Batch Return Aggregation--Status: implemented in backend runtime tests.+### Batch Return Aggregation-Goal:+Current behavior:- define named returns for child workflows that expand into multiple queue rows@@ -752,20 +733,18 @@ Contract:- if a non-batch workflow wants multiple images under one key, it must collect those images into a single list valuebefore returning that key-Tests first:+Validation:- a batched child returning `{image: image_value}` from each child row produces `{image: [image_1, image_2, ...]}`- sibling failure still cancels remaining siblings and fails the parent- duplicate keys inside one child row are rejected rather than silently aggregated-### Stage 5: Frontend Schema, UI, And Docs+### Frontend Schema, UI, And Docs-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.+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.-Goal:+Current behavior:- make named returns usable and visible in the editor@@ -776,14 +755,14 @@ Contract:- `call_saved_workflow` exposes the named return map output- users can wire that output to `workflow_return_get`-Tests first:+Validation:- frontend connection/type tests cover return-value collection wiring- frontend connection/type tests cover wiring one `workflow_return_value.value` directly to `workflow_return.values`- frontend connection/type tests cover `call_saved_workflow.values -> workflow_return_get.values`- docs describe how a called workflow creates named returns and how a caller extracts them-## Frontend Responsibilities In The Long-Term Design+## Frontend ResponsibilitiesThe frontend remains responsible for editor-time behavior:@@ -797,15 +776,9 @@ The frontend remains responsible for editor-time behavior:inputs during backend compatibility evaluation, so workflows that are valid once the caller supplies exposed valuesare not disabled prematurely-Potential future optimization:+## Validation Coverage-- add a backend endpoint that returns a normalized callable workflow interface-- this would let the frontend avoid re-parsing full saved workflow payloads to redraw the node-- it would also give the frontend a backend-authoritative interface hash for drift detection--## Tests Needed Going Forward--Already covered:+Coverage includes:- workflow-call stack and waiting state on `GraphExecutionState`- depth-limit enforcement@@ -820,36 +793,24 @@ Already covered:- literal and connected dynamic call arguments are applied to the child graph at runtime- non-exposed dynamic call arguments are rejected at runtime- child `workflow_return` output is captured and becomes the parent `call_saved_workflow` output-- named `workflow_return` values can be constructed, propagated to the parent, extracted by key, and batch-aggregated as- `dict[str, list[Any]]`+- named `workflow_return` values can be constructed, propagated to the parent, extracted by key, and batch-aggregated+ as `dict[str, list[Any]]`- child workflows without a `workflow_return` node fail cleanly when called- child execution events now include stable workflow-call relationship metadata on the child `SessionQueueItem`- parent-child resume and failure propagation through queue-visible child rows- nested runtime execution with bounded stack depth- direct and generator-backed batch-special child workflows through queue child-row expansion-- compatibility metadata for required exposed inputs, missing/multiple returns, supported named batch-return shapes, and- unsupported batch input wiring+- compatibility metadata for required exposed inputs, missing/multiple returns, supported named batch-return shapes,+ and unsupported batch input wiring-Still needed in later increments:+Supported extension policy:- focused coverage for any newly supported batch or generator shape when its contract changes-- possible migration from dedicated workflow-call queue lifecycle handling to a more general scheduler or- queue-lifecycle model only if another feature needs reusable dependent queue items; the generic record is now the- safe internal seam for that migration--## Recommended Immediate Next Step--The next incremental step should be:--- stop adding feature slices unless they close a concrete correctness gap or unlock a realistic user workflow-- stabilize the current branch with review, targeted test runs, and cleanup of stale design-doc language-- treat migration from `WorkflowCallQueueLifecycle` to a generalized parent/child queue lifecycle as a larger- architecture slice, not as small follow-on busywork+- a more general scheduler or queue-lifecycle model is warranted only if another feature needs reusable dependent queue+ items; the current queue lifecycle remains authoritative-The current branch is at the point where:+## Operational Guidance-- parent call-boundary state exists-- child execution state can be created from the selected saved workflow-- child execution, argument forwarding, explicit return propagation, suspended parent status, queue-visible child rows,- and upward failure cascade work through the current coordinator + queue path-- but long-term generalized parent/child scheduling semantics are still missing+The queue path owns durable child rows, parent waiting/resume transitions, cancellation, retry, recovery, and events.+The generic child record validates identity, ordered aggregation, resource limits, and idempotent terminal events; it+does not replace the queue lifecycle.diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex ed3dc40e5d..d09bcb8b16 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -30,9 +30,9 @@ hierarchy, and they do not return a literal next-node ID. Internal planners andhelpers, while successor readiness is selected from frame-scoped dependencies and effects.Ownership is topology-dependent: admitted fresh `If` branches require matching activation tokens; bounded planners own-admitted loop expansion and continuation. Compatibility adapters own the remaining shapes. Execution ledgers are internal-persistence data, excluded from ordinary model serialization and public schemas. `dump_execution_state()` retains them,-including attached child states. They add no author-time ports or frontend/backend external fields.+admitted loop expansion and continuation. Compatibility adapters own the remaining shapes. Execution ledgers are+internal persistence data, excluded from ordinary model serialization and public schemas. `dump_execution_state()`+retains them, including attached child states. They add no author-time ports or frontend/backend external fields.## Core contract@@ -43,7 +43,8 @@ iteration exposes `item`, `index`, `total`, and `state`; the final execution surLoop state is explicit `LoopState` graph data. It is copied and serialized with normal invocation inputs and results;it is not stored in transient process-local context. If a return omits state, the previous state carries forward. A-missing or `None` continue condition continues; `False` finalizes the current loop after recording its output and state.+missing or `None` continue condition continues; `False` finalizes the current loop after recording its output and+state.The loop is sequential. A body failure or cancellation stops later iterations and does not release partial final-scopedoutputs. An empty collection is successful: no body node runs, `output_collection` is empty, and `final_state` is the@@ -59,9 +60,9 @@ For.item -> body path -> ForReturn.output```This edge is an association, not executable data flow. It is excluded from ordinary input propagation, cycle detection,-and scheduling. The backend requires exactly one outgoing linkage for every `For`, exactly one incoming linkage for every-`ForReturn`, and the exact `For.loop_linkage` to `ForReturn.loop_linkage` endpoints. Default edges using the reserved-`loop_linkage` field are invalid.+and scheduling. The backend requires exactly one outgoing linkage for every `For`, exactly one incoming linkage for+every `ForReturn`, and the exact `For.loop_linkage` to `ForReturn.loop_linkage` endpoints. Default edges using the+reserved `loop_linkage` field are invalid.Authoring workflow JSON may represent the association through a one-to-one connector alias:@@ -78,23 +79,23 @@ unrelated fields.Iteration-scoped outputs (`item`, `index`, `total`, and `state`) define the loop body. Final-scoped outputs(`output_collection` and `final_state`) are available only after the matching loop context completes. Body nodes must-terminate at the linked `ForReturn`; they cannot escape directly to after-loop nodes. Final outputs cannot feed back into-the loop body.+terminate at the linked `ForReturn`; they cannot escape directly to after-loop nodes. Final outputs cannot feed back+into the loop body.-`ForReturn.output` and `ForReturn.state` are scheduler-facing result fields and are hidden as downstream editor outputs.-They are still retained in execution results for aggregation, persistence, and resume. Ordinary state helper nodes-(`state_empty`, `state_get`, `state_set`, and `state_merge`) carry explicit `LoopState` values through the body.+`ForReturn.output` and `ForReturn.state` are scheduler-facing result fields and are hidden as downstream editor+outputs. They are still retained in execution results for aggregation, persistence, and resume. Ordinary state helper+nodes (`state_empty`, `state_get`, `state_set`, and `state_merge`) carry explicit `LoopState` values through the body.## Supported nested shapesNested `For` boundaries are supported recursively when each inner boundary has its own direct linkage and matching`ForReturn`. The inner final collection may feed the parent return directly or through an ordinary parent-scoped-continuation. Independent inner loops must all feed one explicit fan-in continuation; collection concatenation, zipping,-or Cartesian semantics come from the connected collection operation, not from loop scheduling.+continuation. Independent inner loops must all feed one explicit fan-in continuation; collection concatenation,+zipping, or Cartesian semantics come from the connected collection operation, not from loop scheduling.A bounded single internal `Iterate` is supported for the canonical outer-`For` shape: one ordinary preparation node-converts `For.item` to the inner collection, one ordinary body node consumes `Iterate.item`, and one `Collect` collapses-that item dimension before the parent `ForReturn`:+converts `For.item` to the inner collection, one ordinary body node consumes `Iterate.item`, and one `Collect`+collapses that item dimension before the parent `ForReturn`:```textFor.item -> preparation -> Iterate.collection@@ -124,7 +125,7 @@ not admit sibling iterators, fan-in, or additional control-flow nodes.Unsupported shapes, including independent iterator-derived body inputs, mixed nested `For`/`Iterate` bodies, escapingbody paths, ambiguous returns, and arbitrary cyclic graphs, are rejected before execution.-## Generic `For` migration matrix+## Generic `For` routing matrix`_GenericForPlanner` owns these fresh shapes. `_ExecutionMaterializer` remains the compatibility facade for every othershape and for explicitly forced compatibility runs:@@ -139,11 +140,12 @@ shape and for explicitly forced compatibility runs:- Exact bounded outer `For`/`Iterate`/`Collect`.- Exact serial two-`Iterate` nested outer-`For` shape with one ordinary final consumer.-Valid shapes outside this admission matrix retain compatibility ownership, including legacy snapshots, unsupported input-producers, extra nodes or consumers, fan-out, nested `For` depth five or greater, unsupported sibling or deeper shapes,-and saved-workflow or `If`-containing `For` graphs. Malformed linkage, invalid output-scope edges, and unsupported mixed-bodies fail graph validation; a compatibility route does not make them executable. No invocation emits or requires a-literal successor node ID. This matrix changes no invocation, API, saved-workflow, frontend, or generated-schema contract.+Valid shapes outside this admission matrix retain compatibility ownership, including legacy snapshots, unsupported+input producers, extra nodes or consumers, fan-out, nested `For` depth five or greater, unsupported sibling or deeper+shapes, and saved-workflow or `If`-containing `For` graphs. Malformed linkage, invalid output-scope edges, and+unsupported mixed bodies fail graph validation; a compatibility route does not make them executable. No invocation+emits or requires a literal successor node ID. This matrix changes no invocation, API, saved-workflow, frontend, or+generated-schema contract.## Persistence and validation@@ -154,81 +156,69 @@ collections or state.The execution-engine seam is additive to this loop contract. The session runner applies each result through`GraphExecutionState.apply()` using a stable execution reference and records frame-aware output tokens; accepted-`For`/`ForReturn` continuation state is mirrored by a typed, frame-scoped `ContinuationRecord`.-`ForInvocation` and `ForReturnInvocation` also declare one validated, frame-scoped-`continuation` effect per prepared invocation. The `For` effect starts the `for` continuation with the current-iteration and state; the `ForReturn` effect completes it with output, state, and the continue decision. These effects-are persisted under the invocation reference. Session-built effect references carry graph-state, durable-frame,-iteration-path, and workflow-call-depth identity, and stale or cross-scope effects are rejected before mutation. They-never encode `loop_linkage` as a data token. A fresh graph with exactly one static flat `For`/`ForReturn` pair,-including an empty literal collection, a supported non-empty input-driven collection producer, or the exact bounded-empty input-driven producer shape, now uses the generic scheduler adapter for readiness and continuation transitions.-Graph state owns the generic continuation boundary. `_GenericForPlanner` owns admitted For-specific preparation,-materializes the next body iteration, preserves frame paths and carried state, and finalizes nested completion. It-shares only low-level execution-node construction mechanics with the compatibility materializer. An empty literal collection completes through the existing synthetic terminal-`For` result without running the body or `ForReturn`. The generic scheduler remains opaque and never receives a literal-successor node ID. The compatibility continuation bridge is retained only for unsupported loop shapes and explicitly-legacy-loaded snapshots. Empty input-driven shapes outside the exact four-node/four-edge bounded topology, unsupported-input-driven outer collections, five-level-or-deeper or unsupported sibling nested loops, and unsupported mixed control flow remain on the-compatibility scheduler; the exact fresh two-sibling `For`/`ForReturn` `CollectionConcat` fan-in shape, the narrow canonical two-level, and exact fresh three-level and four-level serial nested-`For` shapes-(one literal outer collection, or the exact statically non-empty `CollectionConcat` producer for the three-level case, one direct child at each level, no continuation nodes) and the exact-bounded outer-`For`/`Iterate`/`Collect` shape are now generic-routed. This additive effect seam does not claim generic-scheduling for the remaining shapes. `Iterate` records ordered item tokens in-a closed `StreamBuffer`; an empty `Iterate` records an-explicit empty close. A direct `Iterate.item` consumer waits for the canonical stream to close, then `Collect` consumes-its ordered values; a missing stream falls back to materialized results for legacy snapshots. The exact fresh four-node-`literal collection source -> Iterate -> one ordinary body -> Collect` shape and any number of ordinary downstream-consumers from `Collect.collection` use a private graph-state planner for prepared-copy expansion, iteration paths,-and the empty-stream barrier. The exact fresh two-source/two-`Iterate`/shared-`Collect.item` and exact fresh-three-source/three-`Iterate`/shared-`Collect.item` fan-in shapes also use the planner for independent stream expansion,-closure gating, and deterministic source-ordered hydration. The exact fresh two-branch body-mediated shape,-`source_a -> Iterate_a -> body_a -> Collect.item` plus-`source_b -> Iterate_b -> body_b -> Collect.item`, is also planner-owned:-source IDs are ordered lexically, branch order is preserved, and `Collect` waits-for both streams to close, including empty streams. This is a private bounded-planner case with exactly seven nodes and six ordinary edges: two inputless-ordinary sources, two `Iterate` nodes, two ordinary bodies, and one `Collect`.-It has no `Collect.collection` input, downstream consumer, or extra topology.-Three or more body-mediated branches, fan-in with four or more direct branches, unsupported nested or input-driven-iterator topologies, and mixed control flow outside the bounded per-item `Iterate`/`If`/`Collect` topology remain on-the compatibility materializer. The exact admitted serial nested-`Iterate` chains and producer-driven bounded-`For`/`Iterate`/`Collect` variants use the generic planner described above.-Focused compatibility coverage now proves empty, nested, fan-in, partial/rehydrated, failed, canceled, and retried-Iterate/Collect sessions. This is evidence for the current adapters; it does not remove materialization or queue-ownership. Direct `Iterate`/`Collect`-only graphs and the exact bounded nested shape now use the generic scheduler-adapter: its readiness predicate waits for the canonical stream to close, and completion mirrors Iterate outputs into-that ledger before releasing Collect. Rehydration restores the active class-drain boundary so nested stream order is-preserved across dump/load.-For the exact fresh direct shape, the planner owns expansion, downstream admission, and empty closure atomically: a-failed expansion leaves no partial prepared copies to be resumed. Versioned queue checkpoints and retries preserve the existing durable-execution-state boundary and receive fresh execution identities. Materialization still owns those responsibilities for-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 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.--`GraphExecutionState.complete()` remains the compatibility entry point for callers that already have a node result.-Its first JSON-safe completion uses the same validated, atomic ledger path as `apply()`, including output tokens and+`For`/`ForReturn` continuation state is mirrored by a typed, frame-scoped `ContinuationRecord`. `ForInvocation` and+`ForReturnInvocation` also declare one validated, frame-scoped `continuation` effect per prepared invocation. The `For`+effect starts the `for` continuation with the current iteration and state; the `ForReturn` effect completes it with+output, state, and the continue decision. These effects are persisted under the invocation reference. Session-built+effect references carry graph-state, durable-frame, iteration-path, and workflow-call-depth identity, and stale or+cross-scope effects are rejected before mutation. They never encode `loop_linkage` as a data token. A fresh graph with+exactly one static flat `For`/`ForReturn` pair, including an empty literal collection, a supported non-empty+input-driven collection producer, or the exact bounded empty input-driven producer shape, now uses the generic+scheduler adapter for readiness and continuation transitions. Graph state owns the generic continuation boundary.+`_GenericForPlanner` owns admitted For-specific preparation, materializes the next body iteration, preserves frame+paths and carried state, and finalizes nested completion. It shares only low-level execution-node construction+mechanics with the compatibility materializer. An empty literal collection completes through the existing synthetic+terminal `For` result without running the body or `ForReturn`. The generic scheduler remains opaque and never receives+a literal successor node ID. The compatibility continuation bridge is retained only for unsupported loop shapes and+explicitly legacy-loaded snapshots. Empty input-driven shapes outside the exact four-node/four-edge bounded topology,+unsupported input-driven outer collections, five-level-or-deeper or unsupported sibling nested loops, and unsupported+mixed control flow remain on the compatibility scheduler; the exact fresh two-sibling `For`/`ForReturn`+`CollectionConcat` fan-in shape, the narrow canonical two-level, and exact fresh three-level and four-level serial+nested-`For` shapes (one literal outer collection, or the exact statically non-empty `CollectionConcat` producer for+the three-level case, one direct child at each level, no continuation nodes) and the exact bounded+outer-`For`/`Iterate`/`Collect` shape are now generic-routed. This additive effect seam does not claim generic+scheduling for the remaining shapes. `Iterate` records ordered item tokens in a closed `StreamBuffer`; an empty+`Iterate` records an explicit empty close. A direct `Iterate.item` consumer waits for the canonical stream to close,+then `Collect` consumes its ordered values; a missing stream falls back to materialized results for legacy snapshots.+The exact fresh four-node `literal collection source -> Iterate -> one ordinary body -> Collect` shape and any number+of ordinary downstream consumers from `Collect.collection` use a private graph-state planner for prepared-copy+expansion, iteration paths, and the empty-stream barrier. The exact fresh+two-source/two-`Iterate`/shared-`Collect.item` and exact fresh three-source/three-`Iterate`/shared-`Collect.item`+fan-in shapes also use the planner for independent stream expansion, closure gating, and deterministic source-ordered+hydration. The exact fresh two-branch body-mediated shape, `source_a -> Iterate_a -> body_a -> Collect.item` plus+`source_b -> Iterate_b -> body_b -> Collect.item`, is also planner-owned: source IDs are ordered lexically, branch+order is preserved, and `Collect` waits for both streams to close, including empty streams. This is a private bounded+planner case with exactly seven nodes and six ordinary edges: two inputless ordinary sources, two `Iterate` nodes, two+ordinary bodies, and one `Collect`. It has no `Collect.collection` input, downstream consumer, or extra topology. Three+or more body-mediated branches, fan-in with four or more direct branches, unsupported nested or input-driven iterator+topologies, and mixed control flow outside the bounded per-item `Iterate`/`If`/`Collect` topology remain on the+compatibility materializer. The exact admitted serial nested-`Iterate` chains and producer-driven bounded+`For`/`Iterate`/`Collect` variants use the generic planner described above. Direct `Iterate`/`Collect`-only graphs and+the exact bounded nested shape use the generic scheduler adapter: its readiness predicate waits for the canonical+stream to close, and completion mirrors Iterate outputs into that ledger before releasing Collect. Rehydration restores+the active class-drain boundary so nested stream order is preserved across dump/load. For the exact fresh direct shape,+the planner owns expansion, downstream admission, and empty closure atomically: a failed expansion leaves no partial+prepared copies to be resumed. Versioned queue checkpoints and retries preserve the existing durable execution-state+boundary and receive fresh execution identities. Materialization still owns those responsibilities for 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 behavior preserves 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. Unsupported shapes retain the compatibility continuation/materialization owner.++`GraphExecutionState.complete()` remains the compatibility entry point for callers that already have a node result. Its+first JSON-safe completion uses the same validated, atomic ledger path as `apply()`, including output tokens andsynthetic `For`/`ForReturn` continuation effects. It still permits historical idempotent result replacement for analready-applied node; arbitrary in-memory values that cannot be represented in the JSON ledger remain a scheduler-onlycompatibility case and cannot be persisted. When an explicitly unversioned, partially completed legacy snapshot is@@ -237,42 +227,41 @@ valid. A loaded terminal legacy state may retain its empty in-memory ledger for`dump_execution_state()` upgrades missing loop buckets in the versioned snapshot.`IfInvocation` now declares the same seam for branch activation: it emits one frame-scoped activation token for the-selected branch, and the graph state validates and persists it after invocation. Fresh graphs with one ordinary-node `If`,-the exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no other-consumer, the exact bounded three-`If` chain with direct inner-to-middle-to-outer branch edges, the exact four-`If` nested-chain, or exactly two, exactly three, or exactly four independent ordinary-node sibling `If`s compile opaque, frame-local-activation dependencies in graph state. The three- and four-`If` admissions require `default` edges, all branch inputs-(`condition`, `true_input`, `false_input`) on each `If`. The three-`If` chain permits one extra `middle If.value` edge to-an ordinary leaf consumer with no outputs; that leaf inherits only the outer branch dependency. Other inner/middle outputs-must be direct nested branch edges, and 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 `For`/`ForReturn`, saved-workflow,-legacy, and-five-or-more sibling shapes use the compatibility scheduler with the dedicated-`_IfActivationController` fallback. Legacy snapshots retain their generic compatibility-projection. Legacy-skipped-state projection remains only for old snapshots. Fresh materialization prepares the condition boundary,-resolves the activation token, and attaches only the selected branch input; unselected branch nodes remain unprepared.-The generic and compatibility adapters consume the same decisions and append-only execution edges; no type-specific-branch scheduler prunes edges or propagates skips. Legacy skipped-state metadata remains only for snapshots that already-contain the old projection. `apply()` replaces the activation token by stable identity, and activation effects are-excluded from stream handling. Graph state derives branch membership for the supported fresh shape; the fallback-controller retains it for unsupported and legacy shapes. Author-time-activation+selected branch, and the graph state validates and persists it after invocation. Fresh graphs with one ordinary-node+`If`, the exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no+other consumer, the exact bounded three-`If` chain with direct inner-to-middle-to-outer branch edges, the exact+four-`If` nested chain, or exactly two, exactly three, or exactly four independent ordinary-node sibling `If`s compile+opaque, frame-local activation dependencies in graph state. The three- and four-`If` admissions require `default`+edges, all branch inputs (`condition`, `true_input`, `false_input`) on each `If`. The three-`If` chain permits one+extra `middle If.value` edge to an ordinary leaf consumer with no outputs; that leaf inherits only the outer branch+dependency. Other inner/middle outputs must be direct nested branch edges, and 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 `For`/`ForReturn`, saved-workflow, legacy, and five-or-more sibling+shapes use the compatibility scheduler with the dedicated `_IfActivationController` fallback. Legacy snapshots retain+their generic compatibility projection. Legacy skipped-state projection remains only for old snapshots. Fresh+materialization prepares the condition boundary, resolves the activation token, and attaches only the selected branch+input; unselected branch nodes remain unprepared. The generic and compatibility adapters consume the same decisions and+append-only execution edges; no type-specific branch scheduler prunes edges or propagates skips. Legacy skipped-state+metadata remains only for snapshots that already contain the old projection. `apply()` replaces the activation token by+stable identity, and activation effects are excluded from stream handling. Graph state derives branch membership for+the supported fresh shape; the fallback controller retains it for unsupported and legacy shapes. Author-time activationports and literal successor IDs remain absent, while unsupported loop shapes and saved-workflow control flow remain ontheir compatibility paths until differential coverage proves their generic replacements.-The engine keeps compatibility materialization and queue readiness for loop-containing graphs outside the migration+The engine keeps compatibility materialization and queue readiness for loop-containing graphs outside the routingmatrix 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,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 existing-frontend/backend external interface remains frozen. Branch-membership analysis remains internal, while fresh execution-no longer creates skipped-state projection and old snapshots retain it for compatibility.+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. The execution engine does not modify any file under `invokeai/frontend/...`, including generated schemas; the+existing frontend/backend external interface remains stable. Branch-membership analysis remains internal, while fresh+execution no longer creates skipped-state projection and old snapshots retain it for compatibility.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. The@@ -280,5 +269,5 @@ editor's boundary overlay and contextual `ForReturn` picker are presentation aidvalidation.Collection helpers are ordinary explicit nodes: `CollectionConcat` preserves left-to-right order and accepts unequal-lengths, `CollectionZip` requires equal lengths, and `CollectionCartesian` produces deterministic left-major/right-minor-pairs with a 100,000-pair limit. They do not add implicit loop dimensions.+lengths, `CollectionZip` requires equal lengths, and `CollectionCartesian` produces deterministic+left-major/right-minor pairs with a 100,000-pair limit. They do not add implicit loop dimensions.diff --git a/docs/src/content/docs/features/Workflows/loop-nodes.mdx b/docs/src/content/docs/features/Workflows/loop-nodes.mdxindex 8ab4e4885f..3b82c16395 100644--- a/docs/src/content/docs/features/Workflows/loop-nodes.mdx+++ b/docs/src/content/docs/features/Workflows/loop-nodes.mdx@@ -32,12 +32,12 @@ The `For` node does not send its per-item `item` output directly to nodes afteriterations finish, connect that node to `For.output_collection` or `For.final_state`.The editor draws a dashed green boundary around the loop body. This is a visual guide showing which nodes repeat; the-boundary does not carry data. The dashed green line between `For.loop_linkage` and `ForReturn.loop_linkage` is a required-association, not a data value. The remaining values move through the ports and edges you connect.+boundary does not carry data. The dashed green line between `For.loop_linkage` and `ForReturn.loop_linkage` is a+required association, not a data value. The remaining values move through the ports and edges you connect.The loop is not executable until its two boundary nodes are paired. Connect `For.loop_linkage` directly to the matching-`ForReturn.loop_linkage`. When you add `ForReturn` from an iteration-output connection in the node picker, the editor can-create this association for you. Replacing either boundary node requires pairing the replacement again.+`ForReturn.loop_linkage`. When you add `ForReturn` from an iteration-output connection in the node picker, the editor+can create this association for you. Replacing either boundary node requires pairing the replacement again.Deleting a connector preserves its through-connections by reconnecting the upstream source to surviving downstreamtargets. Deleting a complete loop-linkage alias collapses it to a direct `loop_linkage` edge; ordinary connector paths@@ -63,18 +63,19 @@ port for effects-only bodies.## What The For Outputs Mean-| Output | Meaning | Use it for |-| --- | --- | --- |-| `loop_linkage` | The association port for the matching `ForReturn` | Pairing the loop boundaries; it is not data |-| `item` | The current collection item | The work done during this iteration |-| `index` | The zero-based position of the current item | Labels, counters, or position-based logic |-| `total` | The collection length | Progress or position-based logic |-| `state` | The current loop state | Values carried from earlier iterations |-| `output_collection` | All values returned through `ForReturn.output` | Work that should happen after the loop |-| `final_state` | The state from the last completed iteration | Reading accumulated values after the loop |+| Output | Meaning | Use it for |+| ------------------- | ------------------------------------------------- | ------------------------------------------- |+| `loop_linkage` | The association port for the matching `ForReturn` | Pairing the loop boundaries; it is not data |+| `item` | The current collection item | The work done during this iteration |+| `index` | The zero-based position of the current item | Labels, counters, or position-based logic |+| `total` | The collection length | Progress or position-based logic |+| `state` | The current loop state | Values carried from earlier iterations |+| `output_collection` | All values returned through `ForReturn.output` | Work that should happen after the loop |+| `final_state` | The state from the last completed iteration | Reading accumulated values after the loop |-The `item`, `index`, `total`, and `state` outputs belong inside the loop body. The `output_collection` and `final_state`-outputs become available after the loop finishes. `loop_linkage` is only for pairing the two boundary nodes.+The `item`, `index`, `total`, and `state` outputs belong inside the loop body. The `output_collection` and+`final_state` outputs become available after the loop finishes. `loop_linkage` is only for pairing the two boundary+nodes.Collection Cartesian products are limited to 100,000 item pairs. A product larger than 100,000 pairs fails with anerror instead of expanding without bound.@@ -83,8 +84,8 @@ error instead of expanding without bound.`ForReturn` closes the loop body. It has four useful inputs:-- **Output** adds one value to `For.output_collection` for the current iteration.- Null (`None`) values are retained, so collection positions continue to match iteration order.+- **Output** adds one value to `For.output_collection` for the current iteration. Null (`None`) values are retained, so+ collection positions continue to match iteration order.- **State** supplies the state for the next iteration.- **Continue Condition** controls whether another item should be processed. It continues by default; connecting `False`stops after the current iteration.@@ -164,17 +165,17 @@ Zip: first[0] with second[0], first[1] with second[1], ...Cartesian: every item in first with every item in second```-An empty input to `Concatenate` is harmless. An empty input to `Zip` is valid when both inputs are empty. An empty input-to `Cartesian Product` produces no pairs.+An empty input to `Concatenate` is harmless. An empty input to `Zip` is valid when both inputs are empty. An empty+input to `Cartesian Product` produces no pairs.## For And IterateBoth `For` and `Iterate` repeat work over a collection, but they serve different purposes:-- Use **Iterate** when a normal workflow needs to expand a collection into separate executions and **Collect** when those- executions should be gathered again.-- Use **For** when the repeated work has a clear beginning and end, needs loop state, may stop early, or should expose a- final collection and final state.+- Use **Iterate** when a normal workflow needs to expand a collection into separate executions and **Collect** when+ those executions should be gathered again.+- Use **For** when the repeated work has a clear beginning and end, needs loop state, may stop early, or should expose+ a final collection and final state.An `Iterate` can also be used inside a `For` for a bounded inner pass. The inner values must be gathered by one`Collect` before the outer `ForReturn`:@@ -186,13 +187,11 @@ Collect.collection -> ForReturn.output```The outer loop waits for the inner `Iterate` and `Collect` to finish, then returns one collection for that outer item.-One exact serial two-`Iterate` body is also supported: `For.item` feeds a preparation node and the first `Iterate`;-its item feeds a second preparation node and `Iterate`, followed by one work node, one `Collect`, and `ForReturn`.-For this bounded pattern, use a non-empty literal outer collection and one consumer of `For.output_collection`.-Other arrangements, such as sibling internal `Iterate` nodes or an independent external `Iterate` feeding a `For` body,-are unsupported. The backend has a bounded-two-branch execution-planner case for an internal body-mediated fan-in, but-that implementation detail does not expand the supported workflow contract.+One exact serial two-`Iterate` body is also supported: `For.item` feeds a preparation node and the first `Iterate`; its+item feeds a second preparation node and `Iterate`, followed by one work node, one `Collect`, and `ForReturn`. For this+bounded pattern, use a non-empty literal outer collection and one consumer of `For.output_collection`. Other+arrangements, such as sibling internal `Iterate` nodes or an independent external `Iterate` feeding a `For` body, are+unsupported.## Nested For Loopsdiff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex b894e72b96..66c810ef6f 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -6,179 +6,133 @@ High-level design for the graph module. Focuses on responsibilities, data flow,Provide a typed, acyclic workflow model (**Graph**) plus a runtime scheduler (**GraphExecutionState**) that expandsiterator patterns, tracks readiness via indegree (the number of incoming edges to a node in the directed graph), and-executes nodes from class-grouped ready queues. In normal execution, runtime expansion happens in a separate execution graph-instead of mutating the source graph. Ordinary static DAGs and legacy-shaped `If` graphs use the opaque `ExecutionPlan`-and deterministic `ExecutionScheduler` in `execution_engine/scheduler.py`. Fresh graphs with one ordinary-node `If`, the-exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch and has no other-consumer, the exact bounded three-`If` chain where inner `value` feeds a middle branch and middle `value` feeds an outer-branch, the exact four-`If` nested chain where each `If.value` feeds one-branch port of the next `If`, or exactly two, exactly three, or exactly four-independent ordinary-node sibling `If`s compile opaque, frame-local activation-dependencies in `GraphExecutionState`; unsupported fresh shapes use the compatibility scheduler with the dedicated-`_IfActivationController` fallback, while legacy snapshots retain their generic compatibility projection.-Current fresh sibling support includes exactly four independent `If`s with no nesting, fan-out, or other control-flow-nodes. The bounded three-`If` chain requires direct `default` edges, all three `If`s to have `condition`, `true_input`,-and `false_input` inputs. The inner `If` has only its direct nested branch output; the middle `If.value` may also feed-one ordinary leaf consumer with no outputs. That leaf inherits the outer branch dependency, not middle-`If` polarity.-The exact four-`If` chain has the same input and direct-edge requirements, with no extra-output fan-out. Five or more nested `If`s, other fan-out, mixed graphs outside-the bounded per-item `Iterate`/`If`/`Collect` topology, loop-containing,-saved-workflow, legacy, and five-or-more sibling shapes remain on the-compatibility fallback. Legacy snapshots retain their generic compatibility projection and legacy skipped-state metadata.-Legacy skipped-state projection remains only for old snapshots. Fresh `If` materialization prepares the condition boundary first,-resolves the activation token, and attaches only the selected branch input.-Unselected branch nodes are never prepared, skipped, or added to fresh execution history. Both scheduler adapters-consume these dependency decisions without pruning execution edges or calling a type-specific branch scheduler.-Legacy skipped-state metadata remains only for snapshots that already contain the old projection. Branch-membership-analysis remains an internal author-graph admission decision.-The focused fresh-shape ownership matrix also verifies that supported flat,-nested, bounded fan-out, and four-sibling graphs do not instantiate the-compatibility controller or project fresh skipped nodes in either scheduler-route. This proves the current ownership boundary; it does not remove the-controller, which remains required for unsupported fresh shapes and legacy-snapshots.-The bounded mixed-control-flow gate admits one exact per-item topology: exactly-six nodes and seven edges consisting of an inputless ordinary collection source-feeding `Iterate.collection`, `Iterate.item` feeding `If.condition` and two-distinct ordinary one-input branch adapters, those adapters feeding-`If.true_input` and `If.false_input`, and `If.value` feeding `Collect.item`.-Only this topology uses fresh generic scheduling and frame-local activation-dependencies; alternating true/false items and empty collections preserve-ordered completion. `For`, `ForReturn`, saved-workflow calls,-nested/sibling/fan-in/extra-node variants, legacy snapshots, and all other-mixed graphs remain compatibility-owned. This is backend-only and changes no-invocation, frontend, generated-schema, image, or external-interface contract.-The token-authoritative topology gate is complete for every currently-supported fresh shape listed above. Removing the controller's remaining-author-graph fallback is a separate later gate and remains deferred until-unsupported fresh shapes have their own explicit generic ownership proof.-The bounded If evidence rerun on the current branch passes 639 tests across-the differential, dependency, runtime, SQLite processor, and snapshot-migration 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`, `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 use-the generic adapter. Its adapter-level readiness predicate waits for canonical Iterate streams to close, and generic-completion mirrors each Iterate result into that ledger before releasing `Collect`. The exact fresh four-node shape-`literal collection source -> Iterate -> one ordinary body -> Collect`, plus any number of ordinary downstream+executes nodes from class-grouped ready queues. In normal execution, runtime expansion happens in a separate execution+graph instead of mutating the source graph. Ordinary static DAGs and legacy-shaped `If` graphs use the opaque+`ExecutionPlan` and deterministic `ExecutionScheduler` in `execution_engine/scheduler.py`. Fresh graphs with one+ordinary-node `If`, the exact one-level nested shape with two `If` nodes where the inner value feeds one outer branch+and has no other consumer, the exact bounded three-`If` chain where inner `value` feeds a middle branch and middle+`value` feeds an outer branch, the exact four-`If` nested chain where each `If.value` feeds one branch port of the next+`If`, or exactly two, exactly three, or exactly four independent ordinary-node sibling `If`s compile opaque,+frame-local activation dependencies in `GraphExecutionState`; unsupported fresh shapes use the compatibility scheduler+with the dedicated `_IfActivationController` fallback, while legacy snapshots retain their generic compatibility+projection. Current fresh sibling support includes exactly four independent `If`s with no nesting, fan-out, or other+control-flow nodes. The bounded three-`If` chain requires direct `default` edges, all three `If`s to have `condition`,+`true_input`, and `false_input` inputs. The inner `If` has only its direct nested branch output; the middle `If.value`+may also feed one ordinary leaf consumer with no outputs. That leaf inherits the outer branch dependency, not+middle-`If` polarity. The exact four-`If` chain has the same input and direct-edge requirements, with no extra output+fan-out. Five or more nested `If`s, other fan-out, mixed graphs outside the bounded per-item `Iterate`/`If`/`Collect`+topology, loop-containing, saved-workflow, legacy, and five-or-more sibling shapes remain on the compatibility+fallback. Legacy snapshots retain their generic compatibility projection and legacy skipped-state metadata. Legacy+skipped-state projection remains only for old snapshots. Fresh `If` materialization prepares the condition boundary+first, resolves the activation token, and attaches only the selected branch input. Unselected branch nodes are never+prepared, skipped, or added to fresh execution history. Both scheduler adapters consume these dependency decisions+without pruning execution edges or calling a type-specific branch scheduler. Legacy skipped-state metadata remains only+for snapshots that already contain the old projection. Branch-membership analysis remains an internal author-graph+admission decision. The focused fresh-shape ownership matrix also verifies that supported flat, nested, bounded+fan-out, and four-sibling graphs do not instantiate the compatibility controller or project fresh skipped nodes in+either scheduler route. This proves the current ownership boundary; it does not remove the controller, which remains+required for unsupported fresh shapes and legacy snapshots. The bounded mixed-control-flow gate admits one exact+per-item topology: exactly six nodes and seven edges consisting of an inputless ordinary collection source feeding+`Iterate.collection`, `Iterate.item` feeding `If.condition` and two distinct ordinary one-input branch adapters, those+adapters feeding `If.true_input` and `If.false_input`, and `If.value` feeding `Collect.item`. Only this topology uses+fresh generic scheduling and frame-local activation dependencies; alternating true/false items and empty collections+preserve ordered completion. `For`, `ForReturn`, saved-workflow calls, nested/sibling/fan-in/extra-node variants,+legacy snapshots, and all other mixed graphs remain compatibility-owned. This is backend-only and changes no+invocation, frontend, generated-schema, image, or external-interface contract. The token-authoritative topology is used+for every currently supported fresh shape listed above. The controller remains required for unsupported fresh shapes+and legacy snapshots. 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 use the generic adapter. Its adapter-level readiness predicate waits for canonical Iterate streams to close, and+generic completion mirrors each Iterate result into that ledger before releasing `Collect`. The exact fresh four-node+shape `literal collection source -> Iterate -> one ordinary body -> Collect`, plus any number of ordinary downstreamconsumers from `Collect.collection`, is planned by a private graph-state planner, which owns its prepared-copyexpansion, iteration paths, downstream admission, and explicit empty-stream barrier without calling the legacy-materializer. The exact fresh two-source/two-`Iterate`/shared-`Collect.item` and exact fresh three-source/three-`Iterate`/-shared-`Collect.item` fan-in shapes also use the planner for independent stream expansions, closure gating, and-deterministic source-ordered hydration. The exact fresh two-branch body-mediated shape-`source_a -> Iterate_a -> body_a -> Collect.item` plus-`source_b -> Iterate_b -> body_b -> Collect.item` uses the same planner: source IDs-are ordered lexically, each branch preserves its item order, and `Collect` runs-only after both streams close, including explicit empty closes. This is a-private bounded planner case: exactly seven nodes and six ordinary edges—two-inputless ordinary sources, two `Iterate` nodes, two ordinary bodies, and one-`Collect`; it has no-`Collect.collection` input or downstream/extra topology. It is not a change to-the public workflow contract.-The planner also admits one bounded input-driven extension: one inputless-ordinary collection producer feeds one ordinary collection-preparation node,-which feeds the same `Iterate` -> ordinary body -> `Collect` path, with-ordinary downstream consumers allowed. It owns the preparation input edge,-ordered stream effects, empty closure, checkpoint rehydration, failure,-rollback, and fresh retry behavior for that exact shape. It does not admit-`If`, `For`, `ForReturn`, saved-workflow, nested-`Iterate` chain, fan-in, or-mixed control-flow nodes outside the bounded per-item topology above; those-remain compatibility-owned.-The exact fresh seven-node nested shape `outer For -> ordinary collection-preparation -> Iterate -> ordinary body -> Collect -> linked outer ForReturn`,-with one ordinary `outer For.output_collection` consumer, is also generic-routed.-The nested planner owns per-outer-frame stream expansion, parent-frame stream-identity, empty closure, `Collect` readiness/hydration, checkpoint rehydration,-and failure parity for this shape without calling the materializer's nested-copy-helper. Five-level-or-deeper or sibling nested `For` outside the exact two-sibling `CollectionConcat` fan-in shape, deeper or multiple nested iterators,-other input-driven outer collections, other mixed control flow, and legacy snapshots retain-compatibility materializer ownership.-The exact eight-node producer-driven extension—one inputless ordinary-collection producer feeding `outer For.collection`, with the same nested body-and one ordinary outer-output consumer—is also generic-routed. It owns outer-input hydration, per-outer-frame stream expansion, checkpoint rehydration, and-failure parity; input-driven inner preparation, deeper or multiple nesting,-other mixed control flow, and legacy snapshots remain compatibility-owned.-The exact nine-node producer-driven extension adds the same inputless,-statically non-empty `CollectionConcatInvocation` outer producer to the-three-level serial nested-`For` chain. It is generic-routed with the same-trace, output, checkpoint, and failure guarantees; other producer classes and-deeper, multiple, sibling, mixed, and legacy shapes remain compatibility-owned.-The exact serial two-level extension—`For.item -> preparation1 -> Iterate1 ->-preparation2 -> Iterate2 -> ordinary body -> Collect -> linked ForReturn`, plus-one ordinary outer-output consumer—is also generic-routed. Its planner and-compatibility adapter preserve ordered nested frame paths, close empty streams,-resume from checkpoints, and stop downstream completion on failure/retry. Fan-in,-sibling iterators, input-driven inner preparation, other mixed control flow, deeper-nesting, and legacy snapshots remain compatibility-owned.-The exact five-node/four-edge nested-`Iterate` chain—an inputless ordinary-source feeding `outer Iterate`, whose item feeds one ordinary preparation node,-which feeds `inner Iterate`, whose item feeds one ordinary body—is also-generic-routed. Its private planner owns ordered outer/inner frame expansion,-empty outer and inner closure, source completion, checkpoint rehydration, and-failure parity without calling the compatibility materializer. `For`, `Collect`,-fan-in, sibling iterators, other mixed control flow, and legacy snapshots remain-compatibility-owned; the bounded deeper serial extensions are described next.-The exact seven-node/six-edge serial nested-`Iterate` chain extends this-bounded planner by adding one ordinary preparation/`Iterate` pair between the-outer iterator and body. It owns three-component frame paths, ordered-expansion, empty outer and intermediate streams, source completion, checkpoint-rehydration, and failure parity. The exact nine-node/eight-edge serial chain-extends the same planner to four `Iterate` nodes and four-component frame-paths, with the same empty-stream, checkpoint, source-completion, and failure-parity guarantees. The exact eleven-node/ten-edge serial chain extends the-same planner to five `Iterate` nodes and five-component frame paths, with the-same guarantees.-The exact thirteen-node/twelve-edge serial chain extends the same planner to-six `Iterate` nodes and six-component frame paths, with the same empty-stream,-checkpoint, source-completion, and failure-parity guarantees.-The exact fifteen-node/fourteen-edge serial chain extends the same planner to-seven `Iterate` nodes and seven-component frame paths, with the same empty-stream,-checkpoint, source-completion, and failure-parity guarantees.-Three or more body-mediated branches, fan-in with four or more direct branches,-broader nested iterators, and mixed control flow outside the bounded-per-item topology retain `_ExecutionMaterializer` ownership for copy expansion,-grouping, and empty-source handling. `_GenericGraphSchedulerAdapter` may still-own readiness for these unsupported fresh `Iterate`/`Collect` graphs; the-compatibility materializer owns expansion and materialization. Scheduler/materializer-ownership is topology-dependent: pure legacy `Iterate`/`Collect` uses generic scheduler-readiness with compatibility materializer expansion; forced compatibility and legacy-control-flow paths retain `_ExecutionScheduler` where applicable.--The exact seventeen-node/sixteen-edge serial chain extends the same planner to-eight `Iterate` nodes and eight-component frame paths, with the same-empty-stream, checkpoint, source-completion, and failure-parity guarantees.-Nine-level or deeper chains and all other expanded, fan-in, sibling shapes outside the exact two-sibling `For`/`ForReturn` `CollectionConcat` contract, mixed,-five-level-or-deeper `For`, `Collect`, and legacy shapes remain compatibility-owned.-A fresh graph with exactly one flat `For`/`ForReturn` pair and ordinary body nodes also uses the generic adapter for a-literal collection, a supported non-empty input-driven collection, or the exact four-node/four-edge empty input-driven-shape with one inputless producer and no downstream node. It projects readiness and invokes the graph-state-continuation boundary, which selects the next iteration or finalizes the aggregate without exposing a successor node ID-to the generic scheduler. The admitted For planner owns For-specific preparation, continuation, input hydration,-iteration paths, and body expansion; it shares only low-level execution-node construction mechanics with the-compatibility materializer. Other empty/input-driven shapes, five-level-or-deeper or sibling loops outside the exact-two-sibling nested-`For` `CollectionConcat` fan-in shape, mixed control flow, and saved-workflow calls remain-on the compatibility scheduler until their own differential gates are complete. One narrow fresh two-level nested-`For` shape (one non-empty literal outer-collection, one inner `For` sourced from `outer.item`, and no continuation nodes) now uses the generic adapter;-deeper-than-four-level, multiple-child shapes outside the exact two-sibling `CollectionConcat` fan-in contract, other empty/input-driven, mixed, and legacy-loaded shapes remain compatibility-owned.-The exact fresh three-level serial nested-`For` shape (one literal outer-collection or one statically non-empty `CollectionConcatInvocation` producer,-one direct child at each level, no continuation nodes) also uses the generic adapter. The exact fresh-four-level serial nested-`For` shape (one literal outer collection, one direct child at each level, no continuation-nodes) is also generic-routed. Its deepest-empty behavior matches compatibility at the trace, output, and completion-boundaries; the generic projection may retain synthetic empty-frame records. Five-level-or-deeper and sibling nested-`For` shapes outside the exact two-sibling-`CollectionConcat` fan-in contract remain compatibility-owned.-The runtime also exposes an additive execution-engine seam: frame-scoped gates, ordered streams, continuations, and-authorized child-dependency records are stored in-`invokeai.app.services.shared.execution_engine`; legacy graph and queue behavior is retained behind adapters while-those records become authoritative one behavior at a time.--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.+materializer. The exact fresh two-source/two-`Iterate`/shared-`Collect.item` and exact fresh+three-source/three-`Iterate`/ shared-`Collect.item` fan-in shapes also use the planner for independent stream+expansions, closure gating, and deterministic source-ordered hydration. The exact fresh two-branch body-mediated shape+`source_a -> Iterate_a -> body_a -> Collect.item` plus `source_b -> Iterate_b -> body_b -> Collect.item` uses the same+planner: source IDs are ordered lexically, each branch preserves its item order, and `Collect` runs only after both+streams close, including explicit empty closes. This is a private bounded planner case: exactly seven nodes and six+ordinary edges—two inputless ordinary sources, two `Iterate` nodes, two ordinary bodies, and one `Collect`; it has no+`Collect.collection` input or downstream/extra topology. It is not a change to the public workflow contract. The+planner also admits one bounded input-driven extension: one inputless ordinary collection producer feeds one ordinary+collection-preparation node, which feeds the same `Iterate` -> ordinary body -> `Collect` path, with ordinary+downstream consumers allowed. It owns the preparation input edge, ordered stream effects, empty closure, checkpoint+rehydration, failure, rollback, and fresh retry behavior for that exact shape. It does not admit `If`, `For`,+`ForReturn`, saved-workflow, nested-`Iterate` chain, fan-in, or mixed control-flow nodes outside the bounded per-item+topology above; those remain compatibility-owned. The exact fresh seven-node nested shape+`outer For -> ordinary collection preparation -> Iterate -> ordinary body -> Collect -> linked outer ForReturn`, with+one ordinary `outer For.output_collection` consumer, is also generic-routed. The nested planner owns per-outer-frame+stream expansion, parent-frame stream identity, empty closure, `Collect` readiness/hydration, checkpoint rehydration,+and failure parity for this shape without calling the materializer's nested-copy helper. Five-level-or-deeper or+sibling nested `For` outside the exact two-sibling `CollectionConcat` fan-in shape, deeper or multiple nested+iterators, other input-driven outer collections, other mixed control flow, and legacy snapshots retain compatibility+materializer ownership. The exact eight-node producer-driven extension—one inputless ordinary collection producer+feeding `outer For.collection`, with the same nested body and one ordinary outer-output consumer—is also+generic-routed. It owns outer input hydration, per-outer-frame stream expansion, checkpoint rehydration, and failure+parity; input-driven inner preparation, deeper or multiple nesting, other mixed control flow, and legacy snapshots+remain compatibility-owned. The exact nine-node producer-driven extension adds the same inputless, statically non-empty+`CollectionConcatInvocation` outer producer to the three-level serial nested-`For` chain. It is generic-routed with the+same trace, output, checkpoint, and failure guarantees; other producer classes and deeper, multiple, sibling, mixed,+and legacy shapes remain compatibility-owned. The exact serial two-level+extension—`For.item -> preparation1 -> Iterate1 -> preparation2 -> Iterate2 -> ordinary body -> Collect -> linked ForReturn`,+plus one ordinary outer-output consumer—is also generic-routed. Its planner and compatibility adapter preserve ordered+nested frame paths, close empty streams, resume from checkpoints, and stop downstream completion on failure/retry.+Fan-in, sibling iterators, input-driven inner preparation, other mixed control flow, deeper nesting, and legacy+snapshots remain compatibility-owned. The exact five-node/four-edge nested-`Iterate` chain—an inputless ordinary source+feeding `outer Iterate`, whose item feeds one ordinary preparation node, which feeds `inner Iterate`, whose item feeds+one ordinary body—is also generic-routed. Its private planner owns ordered outer/inner frame expansion, empty outer and+inner closure, source completion, checkpoint rehydration, and failure parity without calling the compatibility+materializer. `For`, `Collect`, fan-in, sibling iterators, other mixed control flow, and legacy snapshots remain+compatibility-owned; the bounded deeper serial extensions are described next. The exact seven-node/six-edge serial+nested-`Iterate` chain extends this bounded planner by adding one ordinary preparation/`Iterate` pair between the outer+iterator and body. It owns three-component frame paths, ordered expansion, empty outer and intermediate streams, source+completion, checkpoint rehydration, and failure parity. The exact nine-node/eight-edge serial chain extends the same+planner to four `Iterate` nodes and four-component frame paths, with the same empty-stream, checkpoint,+source-completion, and failure parity guarantees. The exact eleven-node/ten-edge serial chain extends the same planner+to five `Iterate` nodes and five-component frame paths, with the same guarantees. The exact thirteen-node/twelve-edge+serial chain extends the same planner to six `Iterate` nodes and six-component frame paths, with the same empty-stream,+checkpoint, source-completion, and failure-parity guarantees. The exact fifteen-node/fourteen-edge serial chain extends+the same planner to seven `Iterate` nodes and seven-component frame paths, with the same empty-stream, checkpoint,+source-completion, and failure-parity guarantees. Three or more body-mediated branches, fan-in with four or more direct+branches, broader nested iterators, and mixed control flow outside the bounded per-item topology retain+`_ExecutionMaterializer` ownership for copy expansion, grouping, and empty-source handling.+`_GenericGraphSchedulerAdapter` may still own readiness for these unsupported fresh `Iterate`/`Collect` graphs; the+compatibility materializer owns expansion and materialization. Scheduler/materializer ownership is topology-dependent:+pure legacy `Iterate`/`Collect` uses generic scheduler readiness with compatibility materializer expansion; forced+compatibility and legacy control-flow paths retain `_ExecutionScheduler` where applicable.++The exact seventeen-node/sixteen-edge serial chain extends the same planner to eight `Iterate` nodes and+eight-component frame paths, with the same empty-stream, checkpoint, source-completion, and failure-parity guarantees.+Nine-level or deeper chains and all other expanded, fan-in, sibling shapes outside the exact two-sibling+`For`/`ForReturn` `CollectionConcat` contract, mixed, five-level-or-deeper `For`, `Collect`, and legacy shapes remain+compatibility-owned. A fresh graph with exactly one flat `For`/`ForReturn` pair and ordinary body nodes also uses the+generic adapter for a literal collection, a supported non-empty input-driven collection, or the exact+four-node/four-edge empty input-driven shape with one inputless producer and no downstream node. It projects readiness+and invokes the graph-state continuation boundary, which selects the next iteration or finalizes the aggregate without+exposing a successor node ID to the generic scheduler. The admitted For planner owns For-specific preparation,+continuation, input hydration, iteration paths, and body expansion; it shares only low-level execution-node+construction mechanics with the compatibility materializer. Other empty/input-driven shapes, five-level-or-deeper or+sibling loops outside the exact two-sibling nested-`For` `CollectionConcat` fan-in shape, mixed control flow, and+saved-workflow calls remain on the compatibility scheduler. One narrow fresh two-level nested-`For` shape (one+non-empty literal outer collection, one inner `For` sourced from `outer.item`, and no continuation nodes) now uses the+generic adapter; deeper-than-four-level, multiple-child shapes outside the exact two-sibling `CollectionConcat` fan-in+contract, other empty/input-driven, mixed, and legacy-loaded shapes remain compatibility-owned. The exact fresh+three-level serial nested-`For` shape (one literal outer collection or one statically non-empty+`CollectionConcatInvocation` producer, one direct child at each level, no continuation nodes) also uses the generic+adapter. The exact fresh four-level serial nested-`For` shape (one literal outer collection, one direct child at each+level, no continuation nodes) is also generic-routed. Its deepest-empty behavior matches compatibility at the trace,+output, and completion boundaries; the generic projection may retain synthetic empty-frame records.+Five-level-or-deeper and sibling nested-`For` shapes outside the exact two-sibling `CollectionConcat` fan-in contract+remain compatibility-owned. The runtime exposes an execution-engine seam: frame-scoped gates, ordered streams,+continuations, and authorized child-dependency records are stored in `invokeai.app.services.shared.execution_engine`;+legacy graph and queue behavior is retained behind adapters while those records provide the generic runtime projection+for admitted shapes.++The graph runtime is backend-only. It does not add author-time fields or frontend/backend external fields; the existing+frontend/backend interface remains stable.## 2) Major Data Types@@ -246,11 +200,11 @@ Runs a sequence of checks:Special case:- `call_saved_workflow` currently accepts dynamic destination handles of the form- `saved_workflow_input::{childNodeId}::{childFieldName}` as part of its temporary call-boundary contract.+ `saved_workflow_input::{childNodeId}::{childFieldName}` as part of its dynamic call-boundary contract.- Those handles are allowed through graph validation even though they are not static Python model fields on theinvocation class.- - Runtime later validates them against the selected child workflow's exposed callable interface before applying- values to the child graph.+ - Runtime validates them against the selected child workflow's exposed callable interface before applying values to+ the child graph.- The editor preserves dynamic caller values only while the exposed field type remains compatible; type drift at thesame child node/field path resets to the selected workflow's current initial value.- Saved-workflow picker search is server-backed so large workflow libraries do not require scrolling every page@@ -293,39 +247,33 @@ completion mirrors Iterate outputs into the stream ledger. A fresh graph with onincluding a supported non-empty input-driven collection producer or the exact bounded empty input-driven producershape, also uses the adapter for readiness and continuation transitions; graph state owns the invocation-specificcontinuation boundary while the generic scheduler remains opaque. Other empty or unsupported input-driven shapes,-five-level-or-deeper or sibling loops outside the exact two-sibling nested-`For` `CollectionConcat` fan-in contract, saved-workflow calls, and unsupported mixed control-flow shapes outside the bounded per-item-topology continue to use+five-level-or-deeper or sibling loops outside the exact two-sibling nested-`For` `CollectionConcat` fan-in contract,+saved-workflow calls, and unsupported mixed control-flow shapes outside the bounded per-item topology continue to usethe legacy compatibility scheduler until their differential coverage is complete. The narrow canonical two-level-nested-`For` shape, the canonical outer-`For`/bounded-`Iterate`/`Collect` shape,-the exact five-node nested-`Iterate` chain, and the bounded three-, four-, five-,-and six-, seven-, and eight-level serial nested-`Iterate` chains are generic-routed. The nested `For`-shape has-one ordinary preparation node from `For.item` into `Iterate.collection`, one ordinary body node into `Collect.item`,-the `Collect.collection` output into the linked `ForReturn`, and one final outer-output consumer. Each outer iteration,-including an empty inner collection, remains isolated by its frame path. `Iterate` also records non-empty item streams through the generic effect ledger;-for this exact seven-node shape, the private nested planner owns per-outer-frame-copy expansion, stream identity, empty closure, `Collect` readiness/hydration,-checkpoint rehydration, and failure parity. The exact producer-driven outer-extension described above is also generic-routed. The exact fresh three-level serial nested-`For` shape, including its-statically non-empty producer-driven outer variant, and the exact-fresh four-level serial nested-`For` shape are also generic-routed; five-level-or-deeper or sibling nested `For` outside the exact two-sibling `CollectionConcat` fan-in contract, nine-level-or deeper nested iterators, other input-driven outer collections, mixed control-flow, and legacy snapshots retain compatibility materializer ownership. The-exact nested-`Iterate` chains above do not admit `For`, `Collect`, fan-in, sibling,-or deeper-than-eight-level iterator topology. The-materializer remains authoritative for fallback expansion, iteration paths, collector grouping, and-empty-source compatibility handling. The exact fresh four-node body shape, exact two- or three-stream fan-in shapes,-and exact two-branch body-mediated fan-in use the private planner for those responsibilities; three or more-body-mediated branches and four or more direct streams remain compatibility-owned. Direct `Collect.item`-consumers now use the closed stream ledger when available;-the full Iterate/Collect compatibility matrix covers empty, nested, fan-in, partial rehydration, failure, cancellation,-and retry behavior. This evidence does not remove the materializer or queue adapters.-The SQLite/session boundary also preserves this exact nested shape across-cancellation, simulated interrupted-process startup, and retry: startup-cancels stale in-progress rows without changing the persisted partial snapshot,-while retry creates fresh execution/frame/stream identities and completes the-same outer collection. Broader nested shapes and compatibility-owner removal-remain separate gates.+nested-`For` shape, the canonical outer-`For`/bounded-`Iterate`/`Collect` shape, the exact five-node nested-`Iterate`+chain, and the bounded three-, four-, five-, and six-, seven-, and eight-level serial nested-`Iterate` chains are+generic-routed. The nested `For` shape has one ordinary preparation node from `For.item` into `Iterate.collection`, one+ordinary body node into `Collect.item`, the `Collect.collection` output into the linked `ForReturn`, and one final+outer-output consumer. Each outer iteration, including an empty inner collection, remains isolated by its frame path.+`Iterate` also records non-empty item streams through the generic effect ledger; for this exact seven-node shape, the+private nested planner owns per-outer-frame copy expansion, stream identity, empty closure, `Collect`+readiness/hydration, checkpoint rehydration, and failure parity. The exact producer-driven outer extension described+above is also generic-routed. The exact fresh three-level serial nested-`For` shape, including its statically non-empty+producer-driven outer variant, and the exact fresh four-level serial nested-`For` shape are also generic-routed;+five-level-or-deeper or sibling nested `For` outside the exact two-sibling `CollectionConcat` fan-in contract,+nine-level or deeper nested iterators, other input-driven outer collections, mixed control flow, and legacy snapshots+retain compatibility materializer ownership. The exact nested-`Iterate` chains above do not admit `For`, `Collect`,+fan-in, sibling, or deeper-than-eight-level iterator topology. The materializer remains authoritative for fallback+expansion, iteration paths, collector grouping, and empty-source compatibility handling. The exact fresh four-node body+shape, exact two- or three-stream fan-in shapes, and exact two-branch body-mediated fan-in use the private planner for+those responsibilities; three or more body-mediated branches and four or more direct streams remain+compatibility-owned. Direct `Collect.item` consumers now use the closed stream ledger when available; the full+Iterate/Collect compatibility matrix covers empty, nested, fan-in, partial rehydration, failure, cancellation, and+retry behavior. The materializer and queue adapters remain the compatibility owners for other shapes. The+SQLite/session boundary also preserves this exact nested shape across cancellation, simulated interrupted-process+startup, and retry: startup cancels stale in-progress rows without changing the persisted partial snapshot, while retry+creates fresh execution/frame/stream identities and completes the same outer collection. Broader nested shapes remain+compatibility-owned.The source graph is treated as stable during normal execution, but the runtime object still exposes guarded graphmutation helpers. Those helpers reject changes once the affected nodes have already been prepared or executed.@@ -362,25 +310,26 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre`_active_class: Optional[str]`. Ordinary static DAGs and legacy-shaped `If` graphs derive readiness from the genericscheduler; the `If` adapter stores frame-local activation dependencies whose private gate state plus persisted tokenchecks control generic branch readiness. Supported static flat `For` graphs, the narrow canonical two-level nested- `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 bounded- two- through eight-level serial nested-`Iterate` chains, and the bounded per-item `Iterate`/`If`/`Collect` topology use- the generic adapter for readiness and continuation projection; other unsupported input-driven, nine-level or deeper,- 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 is- deserialized.+ `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 bounded two- through eight-level serial nested-`Iterate` chains, and the bounded per-item+ `Iterate`/`If`/`Collect` topology use the generic adapter for readiness and continuation projection; other+ unsupported input-driven, nine-level or deeper, 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 is deserialized.### 4.2 Core methods-- `next()` Returns the next ready exec node. If none are ready, it asks the admitted planner or compatibility materializer- to expand more source nodes and then retries. If the execution state is paused on a workflow call boundary, it returns- `None` without scheduling more- work. Before returning a node, the runtime helper deep-copies inbound values into the node fields.+- `next()` Returns the next ready exec node. If none are ready, it asks the admitted planner or compatibility+ materializer to expand more source nodes and then retries. If the execution state is paused on a workflow call+ boundary, it returns `None` without scheduling more work. Before returning a node, the runtime helper deep-copies+ inbound values into the node fields.- `complete(node_id, output)` is the compatibility completion boundary. For a first JSON-safe completion it delegatesvalidation and the atomic scheduler/ledger transition to `apply()`, including output tokens and synthetic- continuation effects for direct `For`/`ForReturn` callers. An already-applied node retains the historical- idempotent result-replacement behavior; in-memory values that cannot be represented in the JSON effect ledger use- the scheduler-only compatibility path and are not persistable.+ continuation effects for direct `For`/`ForReturn` callers. An already-applied node retains the historical idempotent+ result-replacement behavior; in-memory values that cannot be represented in the JSON effect ledger use the+ scheduler-only compatibility path and are not persistable.- `apply(execution_ref, output, effects)` validates a result against its prepared node and frame, then applies theresult through the existing scheduler while recording references, output/effect tokens, and JSON-safe effects. Thetransition and ledger update are atomic. Direct `complete()` callers therefore receive the same durable state for@@ -389,8 +338,8 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre#### Current execution-effects seam`InvocationContext` exposes a restricted `execution` facade and the underlying `execution_effects` recorder. The-existing invocation output contract remains unchanged. The session runner calls-`invoke_internal_with_effects()` and passes its `InvocationRunResult` to `GraphExecutionState.apply()`.+existing invocation output contract remains unchanged. The session runner calls `invoke_internal_with_effects()` and+passes its `InvocationRunResult` to `GraphExecutionState.apply()`.The recorder dispatches `emit` and `close_stream` by default. A runner may opt an invocation into lifecycle recordingwith an engine-issued `ChildExecutionCapability`; this records validated `spawn_execution`, `await`, and `fail` effects@@ -398,166 +347,137 @@ and returns a capability-bound child handle. Calls without that capability remairow creation remain owned by graph/queue adapters, so an invocation cannot mutate either directly. A cache hit neversuppresses effects: effect-enabled invocations bypass the ordinary output cache for that dispatch.-`IfInvocation` is the first control-flow invocation to declare an activation-effect contract. It emits one-frame-scoped activation token for the selected `true_input` or `false_input` port; `GraphExecutionState` validates that-port against the producing invocation's declared activation fields and persists it without creating a data stream. On-rehydration, every activation token is bound to a currently prepared owner and its derived execution reference; its-declared port, value, canonical token id, mapping key, and known frame fields must match. Unknown extra frame metadata-remains forward-compatible.-For a fresh generic `If` graph with one ordinary-node `If`, the exact one-level nested shape described above, the exact-bounded three-`If` inner/middle/outer chain (including its single middle-value leaf consumer), the exact four-`If` nested chain,-or exactly two, exactly three, or exactly four independent sibling `If`s,+`IfInvocation` is the first control-flow invocation to declare an activation-effect contract. It emits one frame-scoped+activation token for the selected `true_input` or `false_input` port; `GraphExecutionState` validates that port against+the producing invocation's declared activation fields and persists it without creating a data stream. On rehydration,+every activation token is bound to a currently prepared owner and its derived execution reference; its declared port,+value, canonical token id, mapping key, and known frame fields must match. Unknown extra frame metadata remains+forward-compatible. For a fresh generic `If` graph with one ordinary-node `If`, the exact one-level nested shape+described above, the exact bounded three-`If` inner/middle/outer chain (including its single middle-value leaf+consumer), the exact four-`If` nested chain, or exactly two, exactly three, or exactly four independent sibling `If`s,`GraphExecutionState` compiles opaque, frame-local activation-dependency records privately on each branch-local plannode. Five-or-more nesting, five-or-more sibling `If`s, other fan-out, mixed graphs outside the bounded per-item-`Iterate`/`If`/`Collect` topology, loop-containing, and saved-workflow shapes use-the compatibility scheduler and `_IfActivationController` for the same records; legacy snapshots retain the generic-compatibility projection and legacy skipped-state metadata. The controller-remains the fallback runtime dependency owner, and the schedulers no longer call a legacy compiler. Fresh materialization prepares the condition boundary, resolves the activation token,-and attaches only the selected branch input; rejected branch sources remain unprepared. `_GenericGraphSchedulerAdapter`-consumes those records through the opaque plan: its readiness-callback accepts a node only when the required private `ActivationGate` runtime state is resolved and a matching-persisted activation token is present for its frame, while rejected dependencies cause scheduler discard. Both scheduler-adapters consume these dependency records; neither prunes execution edges or calls a type-specific branch scheduler.-The compatibility path still projects discarded prepared nodes into legacy skipped metadata for rehydration and-completion accounting when loading old execution graphs; fresh runs do not create those nodes. `apply()`-validates and persists the invocation-emitted effect afterward, replacing the compatibility token by stable identity.-Activation effects are excluded from data-stream handling. `IterateInvocation` is the first stream-producing-control-flow invocation on this seam: each non-empty prepared copy emits one ordered `item` effect with its iteration-index, and the final copy emits one `close_stream` effect. Direct Iterate/Collect-only graphs now run through the-generic scheduler adapter; its completion maps these results/effects to the existing frame-scoped iteration-stream-identity, so legacy output mirroring is idempotent. The exact fresh four-node source/Iterate/body/Collect shape,-its ordinary downstream consumers, the exact two- or three-stream fan-in shapes,-and the exact two-branch body-mediated fan-in use the private planner described-above; broader body-mediated fan-in, four or more streams, and other fallback shapes still let the-materializer create-prepared copies, derive iteration paths, group collector inputs, and record the explicit close for an empty source.-For a direct `Iterate.item` edge, the scheduler defers `CollectInvocation` while its canonical stream is open, and-runtime hydration consumes the closed stream in sequence order. If no stream exists, hydration retains the legacy-materialized-result fallback needed by older snapshots. This is not yet token-authoritative downstream topology beyond-the supported direct-planner shape or full `Collect` migration: fallback shapes still let the materializer own copy-expansion, iteration paths, collector grouping, collection-input hydration, and empty-source closure; the exact fresh-four-node source/Iterate/body/Collect shape and any number of ordinary downstream-consumer extensions use the-private planner instead.-No author-time activation ports or literal successor IDs are introduced.+`Iterate`/`If`/`Collect` topology, loop-containing, and saved-workflow shapes use the compatibility scheduler and+`_IfActivationController` for the same records; legacy snapshots retain the generic compatibility projection and legacy+skipped-state metadata. The controller remains the fallback runtime dependency owner, and the schedulers no longer call+a legacy compiler. Fresh materialization prepares the condition boundary, resolves the activation token, and attaches+only the selected branch input; rejected branch sources remain unprepared. `_GenericGraphSchedulerAdapter` consumes+those records through the opaque plan: its readiness callback accepts a node only when the required private+`ActivationGate` runtime state is resolved and a matching persisted activation token is present for its frame, while+rejected dependencies cause scheduler discard. Both scheduler adapters consume these dependency records; neither prunes+execution edges or calls a type-specific branch scheduler. The compatibility path still projects discarded prepared+nodes into legacy skipped metadata for rehydration and completion accounting when loading old execution graphs; fresh+runs do not create those nodes. `apply()` validates and persists the invocation-emitted effect afterward, replacing the+compatibility token by stable identity. Activation effects are excluded from data-stream handling. `IterateInvocation`+is the first stream-producing control-flow invocation on this seam: each non-empty prepared copy emits one ordered+`item` effect with its iteration index, and the final copy emits one `close_stream` effect. Direct Iterate/Collect-only+graphs now run through the generic scheduler adapter; its completion maps these results/effects to the existing+frame-scoped iteration-stream identity, so legacy output mirroring is idempotent. The exact fresh four-node+source/Iterate/body/Collect shape, its ordinary downstream consumers, the exact two- or three-stream fan-in shapes, and+the exact two-branch body-mediated fan-in use the private planner described above; broader body-mediated fan-in, four+or more streams, and other fallback shapes still let the materializer create prepared copies, derive iteration paths,+group collector inputs, and record the explicit close for an empty source. For a direct `Iterate.item` edge, the+scheduler defers `CollectInvocation` while its canonical stream is open, and runtime hydration consumes the closed+stream in sequence order. If no stream exists, hydration retains the legacy materialized-result fallback needed by+older snapshots. This is not yet token-authoritative downstream topology beyond the supported direct-planner shape or+full `Collect` support: fallback shapes still let the materializer own copy expansion, iteration paths, collector+grouping, collection-input hydration, and empty-source closure; the exact fresh four-node source/Iterate/body/Collect+shape and any number of ordinary downstream-consumer extensions use the private planner instead. No author-time+activation ports or literal successor IDs are introduced.For a fresh graph with one static flat `For`/`ForReturn` pair, including the exact empty literal collection case, thesame adapter now projects ordinary readiness and calls the graph-state generic continuation boundary after each`ForReturn` when iterations exist. That boundary carries returned state, honors `continue_condition`, creates the nextprepared iteration when needed, and finalizes `output_collection` and `final_state`. For an empty literal collection,-the generic path completes through the existing synthetic terminal `For` result without running the body or `ForReturn`.-The generic scheduler receives only opaque node IDs and dependencies; it never receives a literal next node ID. The-compatibility continuation bridge remains available only for unsupported loop shapes and explicitly legacy-loaded snapshots.-The exact four-node/four-edge empty input-driven shape with one inputless static-list producer is also generic-routed.-Other input-driven outer collections, five-level-or-deeper or sibling nested loops outside the exact two-sibling `CollectionConcat` fan-in contract, or unsupported mixed loop shapes remain compatibility-owned; the exact fresh two-sibling `For`/`ForReturn` `CollectionConcat` fan-in shape, the narrow canonical two-level, and exact fresh three-level and four-level serial nested-`For` shapes (including the exact three-level producer-driven outer variant), the canonical bounded- internal `Iterate`/`Collect` shape, the exact producer-driven outer nested extension, and the bounded two- through- six-, seven-, and eight-level serial nested-`Iterate` chains are generic-routed. On-rehydration, the generic adapter restores the active class-drain-boundary so an in-flight nested stream resumes in the same frame/sequence order.--For scheduling is linear in the collection size. The continuation transfers ownership of the remaining collection to the-next prepared `For` node instead of deep-copying it at every iteration. Source completion uses a derived, lazy per-source-count of pending prepared executions, and continuation validation uses the existing prepared-`For` index rather than-rescanning every prior iteration. The count is runtime-only and is rebuilt after snapshot rehydration; it does not change-the persisted execution-state or invocation contracts. The focused For performance, collection-ownership, count-invariant,-and generic/compatibility differential tests cover this boundary. The direct Iterate planner has separate readiness-projection costs and is not part of this For-specific optimization.+the generic path completes through the existing synthetic terminal `For` result without running the body or+`ForReturn`. The generic scheduler receives only opaque node IDs and dependencies; it never receives a literal next+node ID. The compatibility continuation bridge remains available only for unsupported loop shapes and explicitly+legacy-loaded snapshots. The exact four-node/four-edge empty input-driven shape with one inputless static-list producer+is also generic-routed. Other input-driven outer collections, five-level-or-deeper or sibling nested loops outside the+exact two-sibling `CollectionConcat` fan-in contract, or unsupported mixed loop shapes remain compatibility-owned; the+exact fresh two-sibling `For`/`ForReturn` `CollectionConcat` fan-in shape, the narrow canonical two-level, and exact+fresh three-level and four-level serial nested-`For` shapes (including the exact three-level producer-driven outer+variant), the canonical bounded internal `Iterate`/`Collect` shape, the exact producer-driven outer nested extension,+and the bounded two- through six-, seven-, and eight-level serial nested-`Iterate` chains are generic-routed. On+rehydration, the generic adapter restores the active class-drain boundary so an in-flight nested stream resumes in the+same frame/sequence order.++For scheduling is linear in the collection size. The continuation transfers ownership of the remaining collection to+the next prepared `For` node instead of deep-copying it at every iteration. Source completion uses a derived, lazy+per-source count of pending prepared executions, and continuation validation uses the existing prepared-`For` index+rather than rescanning every prior iteration. The count is runtime-only and is rebuilt after snapshot rehydration; it+does not change the persisted execution-state or invocation contracts. The focused For performance,+collection-ownership, count-invariant, and generic/compatibility differential tests cover this boundary. The direct+Iterate planner has separate readiness projection costs and is not part of this For-specific optimization.`ExecutionFrame` identifies the owning state, loop iteration path, and workflow-call depth. `ExecutionReference`identifies one prepared execution node and its frame. `ExecutionToken` records an output port, value, frame, tokenkind, and optional sequence. `loop_linkage` remains association metadata and never becomes a data token. This ledger iscurrently additive. Ordinary static-DAG and legacy-shaped `If` readiness comes from the generic scheduler through a-compatibility projection; the activation token is authoritative for generic `If` branch readiness. Supported static flat-`For` readiness and continuation transitions also use the generic adapter, while materialization and type-specific-control paths remain authoritative for unsupported loop shapes and workflow-call graphs. A future-migration may make token-built topology and the remaining control-flow paths authoritative only after compatibility is proven.--The generic scheduler is an in-memory graph-state component only. It does not-create, update, retry, cancel, delete, or recover `SessionQueueItem` rows and-does not own queue statuses or events. A graph containing a saved-workflow call-therefore stays on the legacy scheduler and the dedicated workflow-call queue-adapters.--Target migration contract: control-flow nodes remain concrete invocation-subclasses that declare frame-scoped data, activation, stream-closure, child,-and terminal effects. The generic scheduler selects nodes from required-effects 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;-the supported static flat `For`/`ForReturn` shape, including the non-empty-input-driven producer case, uses it for-frame-scoped continuation effects and generic readiness/continuation-projection.-Direct `Iterate`/`Collect`-only graphs use the generic scheduler adapter for-readiness and completion. The exact fresh four-node source/Iterate/body/Collect-shape, its ordinary downstream-consumer extensions, the exact two- or three-stream-fan-in shapes, and the exact two-branch body-mediated fan-in use the private planner-for expansion and empty-stream closure; broader body-mediated fan-in, four or more streams, workflow-call-invocations, unsupported loop shapes, and mixed control-flow graphs remain on-compatibility paths. `ForInvocation` and-`ForReturnInvocation` now declare one validated, frame-scoped `continuation`-effect per prepared invocation: `For` starts the `for` continuation with its-iteration/state payload, and `ForReturn` completes it with output/state/-continue-decision data. Session-built recorders bind the effect reference to-the graph-state ID, durable frame ID, iteration path, and workflow-call depth;-graph-state validation rejects a stale or cross-frame continuation before-mutation. Graph state persists these effects under the invocation reference-and excludes `loop_linkage` from token data. 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: the generic adapter calls the graph-state generic continuation boundary,-which creates the next prepared iteration, aggregates outputs, and finalizes the-supported flat loop. The compatibility bridge remains for other unsupported input-driven,-five-level-or-deeper/sibling nested outside the exact two-sibling `CollectionConcat` fan-in contract, mixed-loop, and legacy-snapshot execution; those paths-retain their existing materialization and linkage ownership. The supported- fresh static flat `For`/`ForReturn` shape, the exact bounded empty input-driven- flat shape, the narrow canonical two-level and exact fresh three-level and four-level serial nested-`For`- shapes (including the exact three-level producer-driven outer variant),- and the canonical bounded internal `Iterate`/`Collect`-shape use the generic adapter. For-`If`, generic readiness consumes opaque frame-local plan dependencies and requires-both matching private `ActivationGate` runtime state and a persisted activation token. Fresh resolution attaches only-the selected branch edge; the forced compatibility `_ExecutionScheduler` path preserves this behavior for fresh states,-while legacy skipped metadata remains only when loading old discarded projections.-This is not token-built successor topology. Loop and workflow-call adapters-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 boundary-remains frozen: this refactoring does not modify `invokeai/frontend/...` or-existing 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, a constructed-mixed/nested `If` graph, the supported static flat `For`/`ForReturn` shape, the-narrow canonical nested-`For` shape, and the canonical nested-`For`/`Iterate`/`Collect` shape. The latter covers empty inner collections and-dump/load resume ordering.-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 other unsupported input-driven, deeper/multiple,-mixed, or workflow-call loop shapes. Real queue/processor-coverage in `tests/app/services/session_processor/test_if_processor_sqlite.py`-also exercises true and false `If` selection, cancellation before and after-resolution, retry from a canceled SQLite item, fresh execution identities, and-selected-only completion. Stale identity and legacy loop-frame rehydration are-covered separately by the differential and graph-state tests.+compatibility projection; the activation token is authoritative for generic `If` branch readiness. Supported static+flat `For` readiness and continuation transitions also use the generic adapter, while materialization and type-specific+control paths remain authoritative for unsupported loop shapes and workflow-call graphs.++The generic scheduler is an in-memory graph-state component only. It does not create, update, retry, cancel, delete, or+recover `SessionQueueItem` rows and does not own queue statuses or events. A graph containing a saved-workflow call+therefore stays on the legacy scheduler and the dedicated workflow-call queue adapters.++Control-flow nodes remain concrete invocation subclasses that declare frame-scoped data, activation, stream-closure,+child, and terminal effects. The generic scheduler selects nodes from required effects 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; the supported static flat+`For`/`ForReturn` shape, including the non-empty input-driven producer case, uses it for frame-scoped continuation+effects and generic readiness/continuation projection. Direct `Iterate`/`Collect`-only graphs use the generic scheduler+adapter for readiness and completion. The exact fresh four-node source/Iterate/body/Collect shape, its ordinary+downstream-consumer extensions, the exact two- or three-stream fan-in shapes, and the exact two-branch body-mediated+fan-in use the private planner for expansion and empty-stream closure; broader body-mediated fan-in, four or more+streams, workflow-call invocations, unsupported loop shapes, and mixed control-flow graphs remain on compatibility+paths. `ForInvocation` and `ForReturnInvocation` now declare one validated, frame-scoped `continuation` effect per+prepared invocation: `For` starts the `for` continuation with its iteration/state payload, and `ForReturn` completes it+with output/state/ continue-decision data. Session-built recorders bind the effect reference to the graph-state ID,+durable frame ID, iteration path, and workflow-call depth; graph-state validation rejects a stale or cross-frame+continuation before mutation. Graph state persists these effects under the invocation reference and excludes+`loop_linkage` from token data. 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: the generic adapter calls the graph-state generic continuation boundary,+which creates the next prepared iteration, aggregates outputs, and finalizes the supported flat loop. The compatibility+bridge remains for other unsupported input-driven, five-level-or-deeper/sibling nested outside the exact two-sibling+`CollectionConcat` fan-in contract, mixed-loop, and legacy-snapshot execution; those paths retain their existing+materialization and linkage ownership. The supported fresh static flat `For`/`ForReturn` shape, the exact bounded empty+input-driven flat shape, the narrow canonical two-level and exact fresh three-level and four-level serial nested-`For`+shapes (including the exact three-level producer-driven outer variant), and the canonical bounded internal+`Iterate`/`Collect` shape use the generic adapter. For `If`, generic readiness consumes opaque frame-local plan+dependencies and requires both matching private `ActivationGate` runtime state and a persisted activation token. Fresh+resolution attaches only the selected branch edge; the forced compatibility `_ExecutionScheduler` path preserves this+behavior for fresh states, while legacy skipped metadata remains only when loading old discarded projections. This is+not token-built successor topology. Loop and workflow-call adapters still own materialization for unsupported shapes+and durable queue lifecycle. The frontend boundary remains frozen: the graph runtime does not modify+`invokeai/frontend/...` or existing 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, a constructed mixed/nested `If` graph, the supported+static flat `For`/`ForReturn` shape, the narrow canonical nested-`For` shape, and the canonical nested+`For`/`Iterate`/`Collect` shape. The latter covers empty inner collections and dump/load resume ordering. 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, Other unsupported input-driven, deeper/multiple,+mixed, or workflow-call loop shapes remain on their compatibility paths. Real queue/processor coverage in+`tests/app/services/session_processor/test_if_processor_sqlite.py` also exercises true and false `If` selection,+cancellation before and after resolution, retry from a canceled SQLite item, fresh execution identities, and+selected-only completion. Stale identity and legacy loop-frame rehydration are covered separately by the differential+and graph-state tests.Workflow-call note:@@ -565,15 +485,15 @@ Workflow-call note:itself orchestrate child execution.- In the current implementation, `DefaultSessionRunner.run_node()` invokes `CallSavedWorkflowInvocation` through theeffect-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.+ `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.- The `session_queue` schema now has matching columns for those relationship fields, and parent queue items can enter a`waiting` status while suspended on a child workflow execution.-- Queue lifecycle semantics are now partially defined for workflow-call chains:+- Queue lifecycle semantics for workflow-call chains are:- child success resumes the waiting parent- multiple child queue rows may complete under one waiting parent when the called workflow contains direct batchnodes; the parent resumes only after all expected child rows complete@@ -588,7 +508,7 @@ Workflow-call note:- retry is root-oriented and should not be exposed directly on child queue rows in the UI- 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+ - child workflows that mix supported batch nodes with unrelated generator nodes are rejected- The generic `ChildDependencyRecord` now owns the internal child identity, ordered all-of aggregation, capabilityidentity, resource limits, idempotent terminal transition, and parent terminal decision alongside this workflow-calllifecycle. Existing queue fields, statuses, cancellation, retry, and event behavior remain authoritative; queue-row@@ -601,44 +521,43 @@ Workflow-call note:- `_PreparedExecRegistry` Owns the relationship between source graph nodes and prepared execution graph nodes, pluscached metadata such as iteration path and runtime state.- `_ExecutionMaterializer` is the compatibility planner facade. It expands source graph nodes into concrete execution- graph nodes when an unsupported or legacy shape runs out of ready work. On those compatibility paths it owns iterator expansion, collector grouping,- prepared-parent selection, and creation of execution-graph edges. When matching prepared parents for a downstream- exec node, skipped prepared exec nodes are ignored and cannot be selected as live inputs.- The class lives in `graph_materializer.py` and is re-exported by `graph.py`.+ graph nodes when an unsupported or legacy shape runs out of ready work. On those compatibility paths it owns iterator+ expansion, collector grouping, prepared-parent selection, and creation of execution-graph edges. When matching+ prepared parents for a downstream exec node, skipped prepared exec nodes are ignored and cannot be selected as live+ inputs. The class lives in `graph_materializer.py` and is re-exported by `graph.py`.- `_GenericForPlanner` owns admitted fresh `For`/`ForReturn` preparation, continuation transitions, carried state,- frame paths, and nested `For` completion. It uses `_ExecutionNodeBuilder` only for low-level copy, edge, input,- and scheduler-registration mechanics; it does not construct `_ExecutionMaterializer`. Unsupported and legacy shapes+ frame paths, and nested `For` completion. It uses `_ExecutionNodeBuilder` only for low-level copy, edge, input, and+ scheduler-registration mechanics; it does not construct `_ExecutionMaterializer`. Unsupported and legacy shapesretain the compatibility facade.-- Private `graph_iterate_planner.py` expands the supported direct and body-mediated Iterate/Collect shapes.- Graph-state method wrappers preserve the admission, copy creation, edge attachment, and atomic preparation entry- points. The planner continues to use the graph state's journal, mappings, caches, and scheduler.+- Private `graph_iterate_planner.py` expands the supported direct and body-mediated Iterate/Collect shapes. Graph-state+ method wrappers preserve the admission, copy creation, edge attachment, and atomic preparation entry points. The+ planner continues to use the graph state's journal, mappings, caches, and scheduler.- `_IfActivationController` Owns fallback runtime `If` admission and compiles opaque, frame-local activation dependencyrecords for unsupported fresh shapes and legacy prepared nodes. Fresh ordinary-node single-`If` graphs, the bounded- nested pair, the exact bounded three-`If` inner/middle/outer chain, the exact four-`If` nested chain, and exactly two,- exactly three, or exactly four independent sibling `If`s- compile those dependencies in graph state. The bounded three-`If` chain also admits one middle-`If` value fan-out to- one ordinary leaf consumer; that leaf inherits only the outer branch dependency, not middle-`If` polarity. Other- fan-out remains fallback. Fresh admission leaves rejected+ nested pair, the exact bounded three-`If` inner/middle/outer chain, the exact four-`If` nested chain, and exactly+ two, exactly three, or exactly four independent sibling `If`s compile those dependencies in graph state. The bounded+ three-`If` chain also admits one middle-`If` value fan-out to one ordinary leaf consumer; that leaf inherits only the+ outer branch dependency, not middle-`If` polarity. Other fan-out remains fallback. Fresh admission leaves rejectedbranch sources unprepared; legacy skipped-state projections remain loadable.-- Private `graph_if_dependencies.py` compiles fresh activation dependencies, and- `graph_if_runtime.py` records dependencies and evaluates admission against gates and tokens.- `GraphExecutionState` retains the method entry points, durable token/reference/effect storage,- derived caches, transaction journal, and fallback controller selection.+- Private `graph_if_dependencies.py` compiles fresh activation dependencies, and `graph_if_runtime.py` records+ dependencies and evaluates admission against gates and tokens. `GraphExecutionState` retains the method entry points,+ durable token/reference/effect storage, derived caches, transaction journal, and fallback controller selection.- Private `graph_scheduler.py` contains `_ExecutionScheduler` and `_GenericGraphSchedulerAdapter`. `graph.py`deliberately re-exports both classes, preserving their existing import paths and monkeypatch seams while keepingscheduler implementation details out of the graph-state façade.- `_GenericGraphSchedulerAdapter` Projects the generic `ExecutionPlan`/`ExecutionScheduler` into the existing statefields for ordinary static DAGs and legacy-shaped `If` graphs; the generic scheduler owns opaque readiness,- intentional discards, indegree transitions, deterministic ordering, claimed work, and completion. The adapter registers- activation dependencies from graph-state compilation or the fallback controller and checks private gate state plus- persisted activation tokens. Fresh `If`- branch nodes are admitted before materialization; legacy prepared nodes may still be discarded for compatibility.- `If` scheduling does not call a type-specific branch scheduler, prune, or delete execution edges.+ intentional discards, indegree transitions, deterministic ordering, claimed work, and completion. The adapter+ registers activation dependencies from graph-state compilation or the fallback controller and checks private gate+ state plus persisted activation tokens. Fresh `If` branch nodes are admitted before materialization; legacy prepared+ nodes may still be discarded for compatibility. `If` scheduling does not call a type-specific branch scheduler,+ prune, or delete execution edges.- `_ExecutionScheduler` Owns materialized-graph indegree transitions, class-grouped ready queues, downstream release,- control-flow continuation scheduling, and the shared opaque activation-dependency projection for compatibility graphs.+ control-flow continuation scheduling, and the shared opaque activation-dependency projection for compatibility+ graphs.- `_ExecutionRuntime` Owns iteration-path lookup, collect input ordering, and input hydration for prepared exec nodes.- Its implementation lives in the private `graph_execution_runtime.py` module; `graph.py` re-exports the runtime- class and its fan-in record types so existing imports and test seams remain stable.+ Its implementation lives in the private `graph_execution_runtime.py` module; `graph.py` re-exports the runtime class+ and its fan-in record types so existing imports and test seams remain stable.- `ExecutionEngineRuntime` Owns the typed gate, stream, and continuation records used by compatibility adapters. Thecanonical stream for a prepared `IterateInvocation` is keyed by the source iterator and its parent iteration path;its item/close effects and legacy output mirroring update the same idempotent buffer. Direct `CollectInvocation.item`@@ -651,15 +570,14 @@ legacy Iterate results, explicit empty-source closes, For continuation identity,`execution_graph`, `indegree`, `executed`, and `results`. Activation tokens persist; private `ActivationGate` runtimestate does not and is reconstructed from condition results or persisted activation tokens. Pending selected `If` inputsremain excluded from ready-queue projection during rehydration, preserving ready-node order across checkpoints before-the pending `If` is admitted. Before token validation,-missing legacy iteration-path metadata is rebuilt from the prepared execution graph. Persisted activation identity is-then validated fail-closed-against prepared owners, derived references, declared activation fields, canonical ids, and known frame fields; extra-frame metadata is retained. `dump_execution_state()` retains execution references, tokens, effects, and child dependencies,-including those in attached child states. Ordinary model serialization and public schemas omit these four internal ledgers;-private helper objects are not serialized. Queue snapshots carry an additive execution-state version marker and use a-version-aware loader;-legacy unmarked snapshots are treated as version 0, while unreadable snapshots are quarantined by queue service.+the pending `If` is admitted. Before token validation, missing legacy iteration-path metadata is rebuilt from the+prepared execution graph. Persisted activation identity is then validated fail-closed against prepared owners, derived+references, declared activation fields, canonical ids, and known frame fields; extra frame metadata is retained.+`dump_execution_state()` retains execution references, tokens, effects, and child dependencies, including those in+attached child states. Ordinary model serialization and public schemas omit these four internal ledgers; private helper+objects are not serialized. Queue snapshots carry an additive execution-state version marker and use a version-aware+loader; legacy unmarked snapshots are treated as version 0, while unreadable snapshots are quarantined by queue+service.### 4.4 Compatibility preparation (`_prepare()`)@@ -676,10 +594,11 @@ materialization.1. it has *no unexecuted iterator ancestors*.- If the node is a **CollectInvocation**: group prepared parent exec nodes by iteration path and create one collector- exec node per group. A collector collapses the immediate iterator that feeds its `item` input, but preserves enclosing- iterator paths. This lets a shape such as `outer_iter -> inner_collection -> inner_iter -> collect -> consumer`- produce one collected result per outer iteration instead of mixing all inner items into one global collection.- Incoming `collection` inputs are treated as ancestor groups and are copied into each matching descendant item group.+ exec node per group. A collector collapses the immediate iterator that feeds its `item` input, but preserves+ enclosing iterator paths. This lets a shape such as+ `outer_iter -> inner_collection -> inner_iter -> collect -> consumer` produce one collected result per outer+ iteration instead of mixing all inner items into one global collection. Incoming `collection` inputs are treated as+ ancestor groups and are copied into each matching descendant item group.- Otherwise: compute all combinations of prepared iterator ancestors. For each combination, choose the prepared parentfor each upstream by matching iterator ancestry, then create **one** exec node. If a node no longer has visible@@ -698,8 +617,7 @@ materialization.- Cache the preserved iteration path when the materializer has one, such as for grouped collectors.- Wire edges from chosen prepared parents.- Set `indegree = number of unmet inputs` (i.e., parents not yet executed). The generic scheduler mirrors this into- its opaque plan for ordinary static DAGs, legacy-shaped `If` graphs, and- direct `Iterate`/`Collect`-only graphs.+ its opaque plan for ordinary static DAGs, legacy-shaped `If` graphs, and direct `Iterate`/`Collect`-only graphs.- Try to resolve any `If`-specific scheduling state.- If the node is ready and not deferred by an unresolved `If`, enqueue it into its class queue.@@ -712,8 +630,8 @@ materialization.dependencies; legacy skipped metadata remains for old snapshots.- `_get_next_node()` uses the generic scheduler for ordinary static DAGs, legacy-shaped `If` graphs, and the admittedfresh control-flow shapes described above, projecting deterministic class/frame order into the compatibility queues.- Fallback control-flow graphs, including saved-workflow calls, use `_active_class` and the legacy class queues.- No batch-size or fairness cap is currently implemented.+ Fallback control-flow graphs, including saved-workflow calls, use `_active_class` and the legacy class queues. No+ batch-size or fairness cap is currently implemented.#### 4.5.1 Indegree (what it is and how it's used)@@ -752,13 +670,13 @@ Run `C` -> `D:0` -> enqueue `D`. Run `D` -> done.- Once the condition resolves, graph-state activation logic records the selected activation token and attaches only theselected branch input to the pending `If` execution. Branch-exclusive ancestors of the unselected branch are neverprepared, executed, or added to fresh execution history. Unsupported fresh shapes and legacy snapshots use the- compatibility controller. Both scheduler adapters use append-only execution edges; no type-specific branch- scheduler performs pruning or skip propagation.+ compatibility controller. Both scheduler adapters use append-only execution edges; no type-specific branch scheduler+ performs pruning or skip propagation.- Legacy snapshots that already contain skipped prepared nodes retain their compatibility metadata and schedulerprojection. Fresh execution does not create that projection.- The SQLite queue/processor path has evidence for cancellation before and after `If` resolution and retry from each- boundary for both condition polarities. A canceled attempt keeps its activation ledger and cannot resume; retry starts- a fresh state and must emit a fresh matching activation token before selected-only completion.+ boundary for both condition polarities. A canceled attempt keeps its activation ledger and cannot resume; retry+ starts a fresh state and must emit a fresh matching activation token before selected-only completion.- Legacy retired or skipped branch-local exec nodes may still be treated as executed for compatibility scheduling, butthey do not create entries in `results`.- Shared ancestors still execute if they are required by the selected branch or by any other live path in the graph.@@ -790,21 +708,18 @@ In normal execution, all runtime expansion occurs in `execution_graph` with tracactivation token.- `results` and `errors` are keyed by **exec node id**.- Applied execution references are unique to one prepared node and frame; their output/effect records are JSON-safe.-- Output and `emit` effects produce frame-aware tokens. `close_stream` produces a `stream_end` token. Association fields- such as `loop_linkage` are never stored as data tokens.-- A non-empty `IterateInvocation` emits one `item` effect per prepared copy,- with a contiguous sequence beginning at zero, and closes its canonical- source/parent-path stream on the final copy. Exact output mirroring is- idempotent. The private planner closes empty streams for the exact fresh- source/Iterate/body/Collect, exact two- or three-stream fan-in, and exact- two-branch body-mediated fan-in shapes; broader body-mediated fan-in, four or- more streams, and other fallback shapes retain materializer compatibility ownership.-- Collectors wait for available direct Iterate streams to close, then aggregate- their ledger values in stream order and may also merge incoming `collection`- inputs during runtime hydration. A missing ledger remains a legacy snapshot- fallback; stale legacy Iterate result mirrors do not override durable effects.- Collectors nested under iterators preserve enclosing iteration paths, so downstream consumers materialize per enclosing- iteration instead of receiving a mixed collection from unrelated outer iterations.+- Output and `emit` effects produce frame-aware tokens. `close_stream` produces a `stream_end` token. Association+ fields such as `loop_linkage` are never stored as data tokens.+- A non-empty `IterateInvocation` emits one `item` effect per prepared copy, with a contiguous sequence beginning at+ zero, and closes its canonical source/parent-path stream on the final copy. Exact output mirroring is idempotent. The+ private planner closes empty streams for the exact fresh source/Iterate/body/Collect, exact two- or three-stream+ fan-in, and exact two-branch body-mediated fan-in shapes; broader body-mediated fan-in, four or more streams, and+ other fallback shapes retain materializer compatibility ownership.+- Collectors wait for available direct Iterate streams to close, then aggregate their ledger values in stream order and+ may also merge incoming `collection` inputs during runtime hydration. A missing ledger remains a legacy snapshot+ fallback; stale legacy Iterate result mirrors do not override durable effects. Collectors nested under iterators+ preserve enclosing iteration paths, so downstream consumers materialize per enclosing iteration instead of receiving+ a mixed collection from unrelated outer iterations.- Branch-exclusive nodes behind an unselected fresh `If` branch remain unmaterialized. Legacy snapshots may retainskipped nodes for compatibility; they are not failed.@@ -827,8 +742,8 @@ Current limitation:dedicated workflow-call queue lifecycle component; `ChildDependencyRecord` is the generic identity and aggregationseam, not a replacement for durable queue operations.- Called workflows currently require exactly one valid `workflow_return` node to be callable at all.-- A single `workflow_return_value.value` may connect directly to `workflow_return.values`; multiple named return members- should be collected and then connected to `workflow_return.values`.+- A single `workflow_return_value.value` may connect directly to `workflow_return.values`; multiple named return+ members should be collected and then connected to `workflow_return.values`.- Direct batch-special child workflows are now supported by expanding them into multiple child queue rows.- Batch outputs may feed a named `workflow_return_value.value` directly. Parent resume aggregates named return maps as`values: dict[str, list[Any]]`, and all rows in one batch call must return the same key set.diff --git a/invokeai/app/services/shared/execution_engine/__init__.py b/invokeai/app/services/shared/execution_engine/__init__.pyindex 1a303bba2d..2334d14a71 100644--- a/invokeai/app/services/shared/execution_engine/__init__.py+++ b/invokeai/app/services/shared/execution_engine/__init__.py@@ -2,13 +2,10 @@from invokeai.app.services.shared.execution_engine.child import (ChildCompletion,- ChildDependencyCoordinator,ChildDependencyRecord,ChildDependencyUpdate,ChildExecutionCapability,ChildExecutionRecord,- ChildQueueCallbacks,- ChildQueueProtocol,ChildState,ChildTerminalStatus,)@@ -35,13 +32,10 @@ from invokeai.app.services.shared.execution_engine.scheduler import (__all__ = ["ChildCompletion",- "ChildDependencyCoordinator","ChildDependencyRecord","ChildDependencyUpdate","ChildExecutionCapability","ChildExecutionRecord",- "ChildQueueCallbacks",- "ChildQueueProtocol","ChildState","ChildTerminalStatus","ActivationGate",diff --git a/invokeai/app/services/shared/execution_engine/child.py b/invokeai/app/services/shared/execution_engine/child.pyindex 4fbe36c1f3..0f76f28c00 100644--- a/invokeai/app/services/shared/execution_engine/child.py+++ b/invokeai/app/services/shared/execution_engine/child.py@@ -1,16 +1,11 @@-"""Generic, queue-independent parent-child execution primitives.--The records in this module are the persistence boundary for a future generic-child scheduler. They deliberately contain no queue implementation or graph-runtime references. Queue services integrate through ``ChildQueueCallbacks``.-"""+"""Parent-child execution records used by workflow-call runtime state."""from __future__ import annotationsimport threadingfrom collections.abc import Sequencefrom dataclasses import dataclass-from typing import Any, Literal, Protocol+from typing import Any, Literalfrom uuid import uuid4from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, TypeAdapter, field_validator, model_validator@@ -759,111 +754,3 @@ class ChildDependencyRecord(_ChildModel):if not isinstance(other, ChildDependencyRecord):return NotImplementedreturn self.model_dump(mode="python") == other.model_dump(mode="python")---class ChildQueueCallbacks(Protocol):- """Minimal queue boundary used by ``ChildDependencyCoordinator``."""-- def enqueue_child(self, child: ChildExecutionRecord) -> None: ...-- def cancel_child(self, child_execution_id: str, reason: str) -> None: ...-- def resume_parent(self, dependency: ChildDependencyRecord, outputs: dict[str, list[Any]]) -> None: ...-- def fail_parent(self, dependency: ChildDependencyRecord, message: str) -> None: ...-- def cancel_parent(self, dependency: ChildDependencyRecord, message: str) -> None: ...---ChildQueueProtocol = ChildQueueCallbacks---class ChildDependencyCoordinator:- """Apply child lifecycle events and notify an abstract queue boundary."""-- def __init__(self, queue: ChildQueueCallbacks) -> None:- self._queue = queue-- def spawn(- self,- capability: ChildExecutionCapability,- child_execution_ids: Sequence[str],- **kwargs: Any,- ) -> ChildDependencyRecord:- record = capability.create_dependency(child_execution_ids, **kwargs)- enqueued: list[str] = []- try:- for child in record.children:- self._queue.enqueue_child(child)- enqueued.append(child.child_execution_id)- except Exception:- cancel = getattr(self._queue, "cancel_child", None)- if cancel is not None:- for child_id in enqueued:- cancel(child_id, "child dependency enqueue failed")- raise- return record-- def complete(- self,- dependency: ChildDependencyRecord,- child_execution_id: str,- outputs: dict[str, Any] | None = None,- *,- parent_execution_id: str | None = None,- parent_frame: Sequence[int | str] | None = None,- parent_reference_id: str | None = None,- child_frame: Sequence[int | str] | None = None,- ) -> ChildDependencyUpdate:- update = dependency.complete_child(- child_execution_id,- outputs,- parent_execution_id=parent_execution_id,- parent_frame=parent_frame,- parent_reference_id=parent_reference_id,- child_frame=child_frame,- )- self._notify(dependency, update)- return update-- def fail(- self,- dependency: ChildDependencyRecord,- child_execution_id: str,- message: str,- **identity: Any,- ) -> ChildDependencyUpdate:- update = dependency.fail_child(child_execution_id, message, **identity)- self._notify(dependency, update)- return update-- def cancel(- self,- dependency: ChildDependencyRecord,- child_execution_id: str,- message: str = "child canceled",- **identity: Any,- ) -> ChildDependencyUpdate:- update = dependency.cancel_child(child_execution_id, message, **identity)- self._notify(dependency, update)- return update-- def _notify(self, dependency: ChildDependencyRecord, update: ChildDependencyUpdate) -> None:- if not update.changed or not update.terminal:- return- for child_id in update.cancel_child_ids or []:- cancel = getattr(self._queue, "cancel_child", None)- if cancel is not None:- cancel(child_id, update.error_message or "sibling terminated")- if update.status == "completed":- resume = getattr(self._queue, "resume_parent", None)- if resume is not None:- resume(dependency, update.aggregated_outputs)- elif update.parent_action == "failed":- fail = getattr(self._queue, "fail_parent", None)- if fail is not None:- fail(dependency, update.error_message or "child failed")- elif update.parent_action == "canceled":- cancel_parent = getattr(self._queue, "cancel_parent", None)- if cancel_parent is not None:- cancel_parent(dependency, update.error_message or "child canceled")diff --git a/tests/app/services/shared/test_execution_engine_child.py b/tests/app/services/shared/test_execution_engine_child.pyindex 626a84f61e..58027415a0 100644--- a/tests/app/services/shared/test_execution_engine_child.py+++ b/tests/app/services/shared/test_execution_engine_child.py@@ -5,9 +5,7 @@ from pydantic import ValidationErrorfrom invokeai.app.services.shared.execution_engine.child import (ChildCompletion,- ChildDependencyCoordinator,ChildExecutionCapability,- ChildExecutionRecord,ChildTerminalStatus,)@@ -152,39 +150,6 @@ def test_failure_cancels_siblings_and_notifies_parent_once() -> None:assert duplicate.terminal is True-def test_queue_coordinator_enqueues_and_resumes_abstract_parent() -> None:- class Queue:- def __init__(self) -> None:- self.enqueued: list[str] = []- self.resumed: list[dict[str, list[object]]] = []-- def enqueue_child(self, child: ChildExecutionRecord) -> None:- self.enqueued.append(child.child_execution_id)-- def cancel_child(self, child_execution_id: str, reason: str) -> None:- del child_execution_id, reason-- def resume_parent(self, dependency: object, outputs: dict[str, list[object]]) -> None:- del dependency- self.resumed.append(outputs)-- def fail_parent(self, dependency: object, message: str) -> None:- del dependency, message-- def cancel_parent(self, dependency: object, message: str) -> None:- del dependency, message-- queue = Queue()- coordinator = ChildDependencyCoordinator(queue)- dependency = coordinator.spawn(_capability(), ["first", "second"], dependency_id="dependency")- coordinator.complete(dependency, "second", {"value": "second"})- update = coordinator.complete(dependency, "first", {"value": "first"})-- assert queue.enqueued == ["first", "second"]- assert update.status == "completed"- assert queue.resumed == [{"value": ["first", "second"]}]--def test_child_records_are_json_safe_and_round_trip() -> None:dependency = _capability().create_dependency(["child"], dependency_id="dependency")dependency.complete_child("child", {"value": None})