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): add generic runtime compatibility layer
JPPhotod705a35d9e99
diff --git a/docs/src/content/docs/contributing/call-saved-workflow.md b/docs/src/content/docs/contributing/call-saved-workflow.mdindex 6a451f9252..6af3968f99 100644--- a/docs/src/content/docs/contributing/call-saved-workflow.md+++ b/docs/src/content/docs/contributing/call-saved-workflow.md@@ -22,7 +22,15 @@ development later.The execution-engine refactoring does not change the callable node, saved-workflow, or queue interaction contract.Generated API schemas may be regenerated when backend runtime metadata becomes visible in a response, but existingfields, requiredness, statuses, events, and client behavior remain compatible. Frontend application behavior is outside-this execution-engine slice.+this execution-engine slice. No code under `invokeai/frontend/...` may be changed by this refactoring; the existing+frontend/backend external interface is frozen.++The internal generic boundary is implemented in+`invokeai.app.services.shared.execution_engine`. It provides frame-scoped+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@@ -55,13 +63,15 @@ 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 first additive execution-effects seam:+The branch also contains the 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;-- `emit` and `close_stream` are the only currently dispatchable effect kinds;-- `spawn`, `await`, and `fail` remain unsupported, so workflow calls continue through- `WorkflowCallCoordinator` and `WorkflowCallQueueLifecycle` rather than a generic child-execution effect.+- `emit` and `close_stream` are dispatchable by default;+- lifecycle recording for `spawn`, `await`, and `fail` is capability-gated and returns a validated child handle where+ applicable; queue mutation remains in the queue adapter;+- saved workflow calls continue through `WorkflowCallCoordinator` and `WorkflowCallQueueLifecycle`, with a generic+ child dependency record validating their relationship and aggregation.Implemented runtime scaffolding:@@ -183,8 +193,10 @@ What is still not implemented:with a clear domain error- broader child-workflow compatibility coverage still needs to be expanded from real unsupported shapes rather thantrying to interpret every frontend-only workflow representation through the current graph-builder path-- the current workflow-call queue lifecycle is still implemented through dedicated workflow-call runtime classes rather- than a fully generalized parent/child scheduler model+- the queue lifecycle remains implemented by dedicated workflow-call runtime classes, but each waiting call also+ registers an internal `ChildDependencyRecord` with an engine-issued capability. The record validates exact parent+ identity, ordered all-of aggregation, resource limits, and idempotent child terminal events before the existing queue+ adapter resumes, fails, or cancels the parentConclusion:@@ -299,13 +311,13 @@ Current limitation:- connected batch child inputs produced by ordinary non-generator upstream nodes are still not supported and should failearly with a clear unsupported-feature error- the current queue-visible child execution path still relies on `WorkflowCallCoordinator` and- `WorkflowCallQueueLifecycle` to resume or fail parents rather than a more general queue scheduler abstraction-- the current implementation is still an intermediate architecture step, but it is now materially closer to the intended- durable parent/child model than the earlier inline-runner path+ `WorkflowCallQueueLifecycle` to resume or fail parents; the generic child record supplies the identity and+ aggregation boundary without changing the public queue contract### 4a. Queue Lifecycle Contract-The current queue-visible implementation uses the following lifecycle contract:+The current queue-visible implementation uses the following lifecycle contract. The generic child record is an internal+validation and aggregation seam; it does not add queue columns, statuses, events, or frontend handles.- root or parent queue items may enter `waiting` while suspended on a child workflow call- child workflow executions are represented as real queue rows with explicit parent/child relationship metadata@@ -807,7 +819,8 @@ Still needed in later increments:- 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+ 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 Stepdiff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex bf0afecb3b..d4d7a6fe45 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -82,11 +82,18 @@ are persisted through `GraphExecutionState`. Runtime-only queues and metadata arFinalization is keyed by the loop source and its parent iteration path so nested or repeated contexts cannot mix outputcollections or state.-The current execution-effects migration 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 and-accepted effects. Only `emit` and `close_stream` effects are currently dispatchable; `For`, `ForReturn`, `Iterate`, and-`Collect` still use the existing materializer and indegree scheduler. `loop_linkage` remains association metadata and-never becomes a data token.+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 and accepted+effects. Legacy `For`/`ForReturn` continuation scheduling is mirrored by a typed, frame-scoped+`ContinuationRecord`. `Iterate` records ordered item tokens in a closed `StreamBuffer`; an empty `Iterate` records an+explicit empty close. `Collect` consumes that buffer when available and retains the materializer/indegree path as its+compatibility adapter. `loop_linkage` remains association metadata and never becomes a data token.++The engine still owns runtime node materialization and queue readiness for existing snapshots. This is intentional:+the generic records preserve the tested loop semantics first, while the old execution graph remains the fallback for+legacy snapshots and unsupported mixed loop shapes. No activation or stream ports are added to author-time graph JSON.+This migration does not modify code under `invokeai/frontend/...`; the existing frontend/backend external interface+remains frozen.The frontend and backend validate the same boundary rules. Saved workflows preserve node types, field handles, and thedirect linkage edge. The current invocation templates provide output-scope metadata when a workflow is loaded. Thediff --git a/invokeai/app/services/session_processor/workflow_call_runtime.py b/invokeai/app/services/session_processor/workflow_call_runtime.pyindex 94221852c8..59ddcb118a 100644--- a/invokeai/app/services/session_processor/workflow_call_runtime.py+++ b/invokeai/app/services/session_processor/workflow_call_runtime.py@@ -202,11 +202,21 @@ class WorkflowCallQueueLifecycle:returntry:output = self.get_child_workflow_return_output(child_queue_item.session)+ generic_update = parent_queue_item.session.record_generic_child_completion(+ child_queue_item.item_id, output.values+ )should_resume_parent, aggregated_values = (parent_queue_item.session.record_waiting_workflow_call_child_completion(child_queue_item.item_id, output.values))+ if generic_update is not None and generic_update.status == "completed":+ generic_values = {+ key: values[0] if len(values) == 1 else values+ for key, values in generic_update.aggregated_outputs.items()+ }+ if generic_values != aggregated_values:+ raise ValueError("Generic child aggregation disagrees with workflow-call aggregation.")except Exception as e:workflow_call_execution = parent_queue_item.session.waiting_workflow_call_executionif workflow_call_execution is not None:@@ -256,15 +266,16 @@ class WorkflowCallQueueLifecycle:waiting_frame = parent_queue_item.session.waiting_workflow_callif waiting_frame is None:raise ValueError("Parent queue item is missing workflow call waiting state.")+ child_error_message = getattr(child_queue_item, "error_message", None) or (+ f"The selected saved workflow '{waiting_frame.workflow_id}' failed during child execution."+ )workflow_call_execution = parent_queue_item.session.waiting_workflow_call_executionif workflow_call_execution is not None:+ parent_queue_item.session.fail_generic_child(child_queue_item.item_id, child_error_message)self._session_runner._services.session_queue.cancel_workflow_call_children(workflow_call_execution.id,exclude_item_ids={child_queue_item.item_id},)- child_error_message = getattr(child_queue_item, "error_message", None) or (- f"The selected saved workflow '{waiting_frame.workflow_id}' failed during child execution."- )self.fail_waiting_workflow_call(parent_queue_item, child_error_message)try:parent_queue_item = self._session_runner._services.session_queue.get_queue_item(parent_queue_item.item_id)@@ -277,6 +288,7 @@ class WorkflowCallQueueLifecycle:parent_queue_item = self._get_parent_queue_item(child_queue_item)if parent_queue_item is None or parent_queue_item.status == "canceled":return+ parent_queue_item.session.cancel_generic_child(child_queue_item.item_id, "child canceled")self._session_runner._services.session_queue.cancel_queue_item(parent_queue_item.item_id)def run_queue_item(self, queue_item: SessionQueueItem) -> None:diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 36ad8b643f..45dcc803c2 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -7,9 +7,13 @@ 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), andexecutes nodes from class-grouped ready queues. In normal execution, runtime expansion happens in a separate execution graph-instead of mutating the source graph. The runtime also exposes an additive execution-effects seam: invocations return-their existing typed output plus recorded effects, while the current materializer and scheduler remain the execution-authority.+instead of mutating the source graph. 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 code under `invokeai/frontend/...` may be changed, and the existing frontend/backend+external interface remains frozen; generated schemas may change only for additive optional runtime response metadata.## 2) Major Data Types@@ -35,6 +39,16 @@ authority.- **IterateInvocation**: input `collection`, outputs include `item` (and index/total).- **CollectInvocation**: many `item` inputs aggregated to one `collection` output.+### Internal execution-engine records++- `ExecutionFrame`, `ActivationGate`, `StreamBuffer`, and `ContinuationRecord` carry typed runtime identity and+ lifecycle state without changing author-time graph models. Their private registries are rebuilt from persisted graph+ results, tokens, and workflow-call state after rehydration.+- `ChildExecutionCapability`, `ChildExecutionRecord`, and `ChildDependencyRecord` validate authorized parent/child+ relationships, resource limits, ordered all-of aggregation, failure, cancellation, and idempotent completion.+- `ExecutionEngineRuntime` owns these records for one graph state. It is private runtime machinery; it is not a new+ frontend node, input handle, or public workflow contract.+## 3) Graph (author-time model)A container for declared nodes and edges. Does **not** perform iteration expansion.@@ -157,11 +171,11 @@ mutation helpers. Those helpers reject changes once the affected nodes have alreexisting invocation output contract remains unchanged. The session runner calls`invoke_internal_with_effects()` and passes its `InvocationRunResult` to `GraphExecutionState.apply()`.-The current recorder accepts only `emit` and `close_stream`. `spawn`, `await_dependency`, and `fail`, along with-mutation and child-execution effect models, are deliberately rejected until the corresponding dispatcher and queue-semantics exist. `ExecutionInterface.authorize_workflow()` is only usable when the runner supplies an authorization-capability. A cache hit never suppresses effects: effect-enabled invocations bypass the ordinary output cache for that-dispatch.+The recorder dispatches `emit` and `close_stream` by default. A runner may opt an invocation into lifecycle recording+with an engine-issued `ChildExecutionCapability`; this records validated `spawn_execution`, `await`, and `fail` effects+and returns a capability-bound child handle. Calls without that capability remain rejected. Mutation effects and queue+row creation remain owned by graph/queue adapters, so an invocation cannot mutate either directly. A cache hit never+suppresses effects: effect-enabled invocations bypass the ordinary output cache for that dispatch.`ExecutionFrame` identifies the owning state, loop iteration path, and workflow-call depth. `ExecutionReference`identifies one prepared execution node and its frame. `ExecutionToken` records an output port, value, frame, token@@ -197,8 +211,10 @@ Workflow-call note:- child queue-row creation is cleaned up on boundary-setup failure and child fan-out is bounded by remaining queuecapacity- child workflows that mix supported batch nodes with unrelated generator nodes are rejected for now-- This is still an intermediate architecture step and should eventually be replaced by a more general parent/child- execution mechanism rather than workflow-call-specific queue lifecycle handling.+- The generic `ChildDependencyRecord` adapter now validates the same waiting parent, ordered children, capability+ identity, all-of aggregation, resource limits, and terminal transitions alongside this workflow-call lifecycle.+ Existing queue fields, statuses, cancellation, retry, and event behavior remain authoritative; queue-row creation and+ recovery are not silently delegated to an in-memory record.### 4.3 Runtime helper classes@@ -213,14 +229,17 @@ Workflow-call note:- `_ExecutionScheduler` Owns indegree transitions, class-grouped ready queues, and downstream release on completion.- `_ExecutionRuntime` Owns iteration-path lookup, collect input ordering, and input hydration for prepared exec nodes.- `_IfBranchScheduler` Applies lazy `If` semantics by deferring branch-local work until the condition is known, then- releasing the selected branch and skipping the unselected branch.+ lowering the decision to a frame-scoped `ActivationGate` and persisted internal activation token, releasing the+ selected branch, and skipping the unselected branch. Its topology analysis remains a compatibility adapter.+- `ExecutionEngineRuntime` Owns the typed gate, stream, and continuation records used by compatibility adapters.`GraphExecutionState.model_post_init()` rehydrates private runtime helpers and caches after normal construction or a-JSON/model round trip. Rehydration reconstructs prepared exec metadata, cached iteration paths, resolved `If` branch-state when the condition is already available, and ready queues from `execution_graph`, `indegree`, `executed`, and-`results`. Persisted execution references, tokens, and effects remain part of the serialized state; private helper-objects do not. Queue snapshots carry an additive execution-state version marker and use the version-aware loader;-legacy unmarked snapshots are treated as version 0, while unreadable snapshots are quarantined by the queue service.+JSON/model round trip. Rehydration reconstructs prepared exec metadata, cached iteration paths, resolved `If` gate+state from condition results or activation tokens, closed iteration streams from durable Iterate results or completed+empty-source state, For continuation identity, and ready queues from `execution_graph`, `indegree`, `executed`, and+`results`. Persisted execution references, tokens, and effects remain part of the serialized state; private helper objects+do not. Queue snapshots carry an additive execution-state version marker and use the version-aware loader; legacy unmarked snapshots+are treated as version 0, while unreadable snapshots are quarantined by the queue service.### 4.4 Preparation (`_prepare()`)@@ -341,17 +360,17 @@ In normal execution, all runtime expansion occurs in `execution_graph` with tracthis file accepts them as `AnyInvocation`.- **Scheduling policy**: adjust `ready_order` to prioritize class queues. A batch-size or fairness cap is not currentlyimplemented.-- **Dynamic behaviors** (future): can be lowered to execution effects and frame/token primitives once their validation,- authorization, persistence, and queue semantics are implemented. Current `apply()` accepts only output, `emit`, and- `close_stream` behavior.+- **Dynamic behaviors**: effect-enabled invocations may record frame-scoped stream, activation, and authorized child+ lifecycle intent. `GraphExecutionState.apply()` remains the transactional graph boundary and rejects mutation or+ queue effects unless a matching adapter owns their application.- **Workflow call boundaries**: `GraphExecutionState` can suspend a parent execution state on a workflow call, attach achild execution state, and later resume the parent without mutating the source graph.Current limitation:-- Child workflow executions are now represented as first-class queue items. Parent resume/failure is intentionally- handled by a dedicated workflow-call queue lifecycle component for this PR because no other feature currently needs a- generalized dependent-queue scheduler.+- Child workflow executions are represented as first-class queue items. Parent resume/failure remains handled by the+ dedicated workflow-call queue lifecycle component; `ChildDependencyRecord` is the generic identity and aggregation+ seam, 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 membersshould be collected and then connected to `workflow_return.values`.diff --git a/invokeai/app/services/shared/execution_effects.py b/invokeai/app/services/shared/execution_effects.pyindex e2c157ce28..bd033b875b 100644--- a/invokeai/app/services/shared/execution_effects.py+++ b/invokeai/app/services/shared/execution_effects.py@@ -9,6 +9,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Callable, Literal, Union+from uuid import uuid4from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, field_validator, model_validatorfrom pydantic_core import PydanticSerializationError@@ -16,6 +17,7 @@ from pydantic_core import PydanticSerializationErrorif TYPE_CHECKING:from invokeai.app.invocations.baseinvocation import BaseInvocationOutput+from invokeai.app.services.shared.execution_engine.child import ChildExecutionCapability_JSON_SERIALIZER = TypeAdapter(Any)@@ -408,13 +410,51 @@ class ExecutionInterface:child_execution_id: str | None = None,authorization_context: dict[str, Any] | None = None,) -> "ChildExecutionHandle":- raise UnsupportedExecutionEffectError("Execution effect kind 'spawn_execution' is not supported")+ capability = self._require_lifecycle_capability("spawn_execution")+ if authorization_context is not None and authorization_context != capability.authorization_context:+ raise PermissionError("child authorization context does not match capability")+ child_id = child_execution_id or str(uuid4())+ child = capability.create_child(child_id, graph=graph, inputs=inputs)+ parent = self._recorder.execution_ref+ self._recorder.record(+ SpawnExecutionEffect(+ execution_ref=parent,+ parent=parent,+ graph=graph,+ inputs=inputs,+ child_execution_id=child.child_execution_id,+ authorization_context=authorization_context+ if authorization_context is not None+ else capability.authorization_context,+ )+ )+ return ChildExecutionHandle(+ child_execution_id=child.child_execution_id,+ parent_execution_id=capability.parent_execution_id,+ authorization_context=authorization_context+ if authorization_context is not None+ else capability.authorization_context,+ )def await_dependency(self, dependency: ExecutionRef) -> None:- raise UnsupportedExecutionEffectError("Execution effect kind 'await' is not supported")+ self._require_lifecycle_capability("await")+ self._recorder.record(AwaitEffect(execution_ref=self._recorder.execution_ref, dependency=dependency))def fail(self, message: str) -> None:- raise UnsupportedExecutionEffectError("Execution effect kind 'fail' is not supported")+ self._require_lifecycle_capability("fail")+ self._recorder.record(FailEffect(execution_ref=self._recorder.execution_ref, message=message))++ def _require_lifecycle_capability(self, effect_kind: str) -> ChildExecutionCapability:+ if not self._recorder.allow_lifecycle_effects:+ raise UnsupportedExecutionEffectError(f"Execution effect kind '{effect_kind}' is not supported")+ capability = self._recorder.child_capability+ if capability is None:+ raise PermissionError("child execution capability is unavailable")+ if capability.parent_execution_id != self._recorder.source_node_id:+ raise PermissionError("child execution capability belongs to another execution")+ if capability.parent_frame != tuple(self._recorder.frame_path):+ raise PermissionError("child execution capability belongs to another execution frame")+ return capabilitydef authorize_workflow(self, workflow_id: str) -> Any:if self._authorize_workflow is None:@@ -486,15 +526,28 @@ class ExecutionEffectsRecorder:_SUPPORTED_EFFECT_KINDS = frozenset({"emit", "close_stream"})- def __init__(self, source_node_id: str = "context", frame_path: tuple[int | str, ...] = ()) -> None:+ def __init__(+ self,+ source_node_id: str = "context",+ frame_path: tuple[int | str, ...] = (),+ *,+ allow_lifecycle_effects: bool = False,+ child_capability: ChildExecutionCapability | None = None,+ ) -> None:self._effects: list[ExecutionEffect] = []self.source_node_id = source_node_idself.frame_path = frame_path+ self.allow_lifecycle_effects = allow_lifecycle_effects+ self.child_capability = child_capability+ self.execution_ref = ExecutionRef(execution_node_id=source_node_id, frame_path=frame_path)def record(self, effect: ExecutionEffect) -> None:if not isinstance(effect, ExecutionEffect):raise TypeError(f"Expected ExecutionEffect, got {type(effect).__name__}")- if effect.kind not in self._SUPPORTED_EFFECT_KINDS:+ supported_effect_kinds = self._SUPPORTED_EFFECT_KINDS+ if self.allow_lifecycle_effects:+ supported_effect_kinds = supported_effect_kinds | {"spawn_execution", "await", "fail"}+ if effect.kind not in supported_effect_kinds:raise UnsupportedExecutionEffectError(f"Execution effect kind '{effect.kind}' is not supported")try:effect.model_dump(mode="json", warnings="error")diff --git a/invokeai/app/services/shared/execution_engine/__init__.py b/invokeai/app/services/shared/execution_engine/__init__.pynew file mode 100644index 0000000000..39b11e0fe5--- /dev/null+++ b/invokeai/app/services/shared/execution_engine/__init__.py@@ -0,0 +1,53 @@+"""Generic execution-engine persistence primitives."""++from invokeai.app.services.shared.execution_engine.child import (+ ChildCompletion,+ ChildDependencyCoordinator,+ ChildDependencyRecord,+ ChildDependencyUpdate,+ ChildExecutionCapability,+ ChildExecutionRecord,+ ChildQueueCallbacks,+ ChildQueueProtocol,+ ChildState,+ ChildTerminalStatus,+)+from invokeai.app.services.shared.execution_engine.primitives import (+ ActivationGate,+ ActivationStatus,+ ContinuationRecord,+ ContinuationStatus,+ ExecutionFrame,+ ExecutionFrameIdentity,+ FrameIdentity,+ StreamBuffer,+ StreamData,+ StreamEnd,+ StreamEvent,+)+from invokeai.app.services.shared.execution_engine.runtime import ExecutionEngineRuntime++__all__ = [+ "ChildCompletion",+ "ChildDependencyCoordinator",+ "ChildDependencyRecord",+ "ChildDependencyUpdate",+ "ChildExecutionCapability",+ "ChildExecutionRecord",+ "ChildQueueCallbacks",+ "ChildQueueProtocol",+ "ChildState",+ "ChildTerminalStatus",+ "ActivationGate",+ "ActivationStatus",+ "ContinuationRecord",+ "ContinuationStatus",+ "ExecutionFrame",+ "ExecutionFrameIdentity",+ "FrameIdentity",+ "StreamBuffer",+ "StreamData",+ "StreamEnd",+ "StreamEvent",+ "ExecutionEngineRuntime",+]diff --git a/invokeai/app/services/shared/execution_engine/child.py b/invokeai/app/services/shared/execution_engine/child.pynew file mode 100644index 0000000000..4fbe36c1f3--- /dev/null+++ b/invokeai/app/services/shared/execution_engine/child.py@@ -0,0 +1,869 @@+"""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``.+"""++from __future__ import annotations++import threading+from collections.abc import Sequence+from dataclasses import dataclass+from typing import Any, Literal, Protocol+from uuid import uuid4++from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, TypeAdapter, field_validator, model_validator+from pydantic_core import PydanticSerializationError++ChildTerminalStatus = Literal["completed", "failed", "canceled"]+ChildState = Literal["pending", "queued", "running", "completed", "failed", "canceled"]+ChildDependencyStatus = Literal["waiting", "running", "completed", "failed", "canceled"]+ChildFailurePolicy = Literal["fail_parent", "cancel_siblings", "continue"]+ChildCancellationPolicy = Literal["cancel_parent", "cancel_siblings", "continue"]++_JSON_SERIALIZER = TypeAdapter(Any)+_TERMINAL_STATES = frozenset({"completed", "failed", "canceled"})+++def _json_safe(value: Any) -> Any:+ try:+ _JSON_SERIALIZER.dump_python(value, mode="json", warnings="error")+ except (PydanticSerializationError, TypeError, ValueError) as exc:+ raise ValueError("must be JSON-serializable") from exc+ return value+++def _frame(value: Any) -> tuple[int | str, ...]:+ if value is None:+ return ()+ if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):+ raise ValueError("frame must be a sequence of integers or strings")+ result: list[int | str] = []+ for part in value:+ if isinstance(part, bool) or not isinstance(part, (int, str)):+ raise ValueError("frame values must be integers or strings")+ if isinstance(part, int) and part < 0:+ raise ValueError("frame values must be non-negative")+ if isinstance(part, str) and not part.strip():+ raise ValueError("frame values must not be blank")+ result.append(part)+ return tuple(result)+++def _id(value: str, label: str) -> str:+ if not isinstance(value, str) or not value.strip():+ raise ValueError(f"{label} must not be blank")+ return value+++class _ChildModel(BaseModel):+ model_config = ConfigDict(extra="forbid", populate_by_name=True)+++class ChildExecutionRecord(_ChildModel):+ """Durable identity and payload for one child execution."""++ child_execution_id: str = Field(min_length=1)+ parent_execution_id: str = Field(min_length=1)+ parent_frame: tuple[int | str, ...] = Field(default_factory=tuple)+ parent_reference_id: str | None = Field(default=None, min_length=1)+ child_frame: tuple[int | str, ...] = Field(default_factory=tuple)+ depth: int = Field(default=0, ge=0)+ enqueue_index: int = Field(default=0, ge=0)+ capability_id: str | None = Field(default=None, min_length=1)+ graph: Any | None = None+ inputs: dict[str, Any] = Field(default_factory=dict)+ state: ChildState = "pending"++ _validate_parent_frame = field_validator("parent_frame", mode="before")(_frame)+ _validate_child_frame = field_validator("child_frame", mode="before")(_frame)+ _validate_graph = field_validator("graph")(_json_safe)+ _validate_inputs = field_validator("inputs")(_json_safe)++ @model_validator(mode="after")+ def _validate_child_scope(self) -> "ChildExecutionRecord":+ if self.depth < 1:+ raise ValueError("child depth must be at least one")+ if (+ len(self.child_frame) <= len(self.parent_frame)+ or self.child_frame[: len(self.parent_frame)] != self.parent_frame+ ):+ raise ValueError("child frame must descend from the authorized parent frame")+ return self++ @field_validator("child_execution_id", "parent_execution_id")+ @classmethod+ def _validate_ids(cls, value: str) -> str:+ return _id(value, "execution id")++ @field_validator("parent_reference_id", "capability_id")+ @classmethod+ def _validate_optional_ids(cls, value: str | None) -> str | None:+ return None if value is None else _id(value, "identity")++ @field_validator("inputs")+ @classmethod+ def _validate_input_names(cls, value: dict[str, Any]) -> dict[str, Any]:+ if any(not name.strip() for name in value):+ raise ValueError("child input names must not be blank")+ return value++ @property+ def id(self) -> str:+ return self.child_execution_id+++class ChildCompletion(_ChildModel):+ """One terminal child result, including its ownership proof."""++ child_execution_id: str = Field(min_length=1)+ parent_execution_id: str = Field(min_length=1)+ parent_frame: tuple[int | str, ...] = Field(default_factory=tuple)+ parent_reference_id: str | None = Field(default=None, min_length=1)+ child_frame: tuple[int | str, ...] = Field(default_factory=tuple)+ status: ChildTerminalStatus+ outputs: dict[str, Any] = Field(default_factory=dict)+ error_message: str | None = None++ _validate_parent_frame = field_validator("parent_frame", mode="before")(_frame)+ _validate_child_frame = field_validator("child_frame", mode="before")(_frame)+ _validate_outputs = field_validator("outputs")(_json_safe)++ @field_validator("child_execution_id", "parent_execution_id")+ @classmethod+ def _validate_ids(cls, value: str) -> str:+ return _id(value, "execution id")++ @field_validator("parent_reference_id")+ @classmethod+ def _validate_reference_id(cls, value: str | None) -> str | None:+ return None if value is None else _id(value, "parent reference id")++ @model_validator(mode="after")+ def _validate_terminal_message(self) -> "ChildCompletion":+ if self.status == "failed" and self.error_message is None:+ raise ValueError("failed child completion requires an error message")+ if self.error_message is not None:+ _id(self.error_message, "child error message")+ return self+++@dataclass(frozen=True)+class ChildDependencyUpdate:+ """Result of applying one child terminal event.++ ``terminal`` means dependency became terminal, not merely that child+ reached a terminal state. Tuple unpacking keeps compatibility with the+ existing ``(is_complete, outputs)`` workflow-call helper shape.+ """++ changed: bool+ terminal: bool+ status: ChildDependencyStatus+ aggregated_outputs: dict[str, list[Any]]+ parent_action: Literal["failed", "canceled"] | None = None+ cancel_child_ids: list[str] | None = None+ error_message: str | None = None++ def __iter__(self):+ yield self.terminal+ yield self.aggregated_outputs++ @property+ def is_complete(self) -> bool:+ return self.terminal++ @property+ def outputs(self) -> dict[str, list[Any]]:+ return self.aggregated_outputs+++class ChildExecutionCapability(_ChildModel):+ """Authorized, immutable authority to create children for one parent frame."""++ capability_id: str = Field(default_factory=lambda: str(uuid4()), min_length=1)+ parent_execution_id: str = Field(min_length=1)+ parent_frame: tuple[int | str, ...] = Field(default_factory=tuple)+ parent_reference_id: str | None = Field(default=None, min_length=1)+ authorized: Literal[True] = True+ authorization_context: dict[str, Any] | None = None+ depth: int = Field(default=0, ge=0)+ max_depth: int = Field(default=64, ge=0)+ max_children: int = Field(default=1000, ge=1)+ capacity: int = Field(default=1000, ge=0)+ failure_policy: ChildFailurePolicy = "fail_parent"+ cancellation_policy: ChildCancellationPolicy = "cancel_parent"++ model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True)++ _validate_parent_frame = field_validator("parent_frame", mode="before")(_frame)+ _validate_authorization_context = field_validator("authorization_context")(_json_safe)++ _issued_children: dict[str, ChildExecutionRecord] = PrivateAttr(default_factory=dict)+ _lock: Any = PrivateAttr(default_factory=threading.RLock)++ @field_validator("parent_execution_id", "capability_id")+ @classmethod+ def _validate_ids(cls, value: str) -> str:+ return _id(value, "execution id")++ @field_validator("parent_reference_id")+ @classmethod+ def _validate_reference_id(cls, value: str | None) -> str | None:+ return None if value is None else _id(value, "parent reference id")++ @model_validator(mode="after")+ def _validate_limits(self) -> "ChildExecutionCapability":+ if self.depth > self.max_depth:+ raise ValueError("depth must not exceed max_depth")+ return self++ @property+ def remaining_capacity(self) -> int:+ with self._lock:+ return max(0, min(self.capacity, self.max_children) - len(self._issued_children))++ def _check_available(self, count: int) -> None:+ with self._lock:+ issued = len(self._issued_children)+ if issued + count > self.max_children:+ raise ValueError(f"maximum child count exceeded ({self.max_children})")+ if issued + count > self.capacity:+ raise ValueError(f"child queue capacity exceeded ({self.capacity})")++ def _check_parent(+ self,+ parent_execution_id: str | None,+ parent_frame: Sequence[int | str] | None,+ parent_reference_id: str | None,+ ) -> None:+ if parent_execution_id is not None and parent_execution_id != self.parent_execution_id:+ raise ValueError("parent execution identity does not match capability")+ if parent_frame is not None and _frame(parent_frame) != self.parent_frame:+ raise ValueError("parent frame does not match capability")+ if parent_reference_id is not None and parent_reference_id != self.parent_reference_id:+ raise ValueError("parent reference identity does not match capability")++ def _check_count(self, count: int) -> None:+ if count < 1:+ raise ValueError("child dependency must contain at least one child")+ if count > self.max_children:+ raise ValueError(f"maximum child count exceeded ({self.max_children})")+ if count > self.capacity:+ raise ValueError(f"child queue capacity exceeded ({self.capacity})")+ if self.depth + 1 > self.max_depth:+ raise ValueError(f"maximum child depth exceeded ({self.max_depth})")++ def create_child(+ self,+ child_execution_id: str,+ *,+ graph: Any | None = None,+ inputs: dict[str, Any] | None = None,+ child_frame: Sequence[int | str] | None = None,+ parent_execution_id: str | None = None,+ parent_frame: Sequence[int | str] | None = None,+ parent_reference_id: str | None = None,+ ) -> ChildExecutionRecord:+ self._check_parent(parent_execution_id, parent_frame, parent_reference_id)+ self._check_count(1)+ child_id = _id(child_execution_id, "child execution id")+ resolved_frame = _frame(child_frame) if child_frame is not None else (*self.parent_frame, child_id)+ if (+ len(resolved_frame) <= len(self.parent_frame)+ or resolved_frame[: len(self.parent_frame)] != self.parent_frame+ ):+ raise ValueError("child frame must descend from the authorized parent frame")+ child = ChildExecutionRecord(+ child_execution_id=child_id,+ parent_execution_id=self.parent_execution_id,+ parent_frame=self.parent_frame,+ parent_reference_id=self.parent_reference_id,+ child_frame=resolved_frame,+ depth=self.depth + 1,+ capability_id=self.capability_id,+ graph=graph,+ inputs={} if inputs is None else inputs,+ )+ with self._lock:+ existing = self._issued_children.get(child_id)+ if existing is not None:+ if existing == child:+ return existing.model_copy(deep=True)+ raise ValueError("child execution id was already issued with different data")+ self._check_available(1)+ self._issued_children[child_id] = child+ return child++ spawn = create_child++ def create_dependency(+ self,+ child_execution_ids: Sequence[str] | None = None,+ *,+ children: Sequence[ChildExecutionRecord] | None = None,+ graph: Any | None = None,+ inputs: dict[str, Any] | None = None,+ child_frames: Sequence[Sequence[int | str]] | None = None,+ child_graphs: Sequence[Any | None] | None = None,+ child_inputs: Sequence[dict[str, Any]] | None = None,+ dependency_id: str | None = None,+ parent_execution_id: str | None = None,+ parent_frame: Sequence[int | str] | None = None,+ parent_reference_id: str | None = None,+ failure_policy: ChildFailurePolicy | None = None,+ cancellation_policy: ChildCancellationPolicy | None = None,+ ) -> "ChildDependencyRecord":+ self._check_parent(parent_execution_id, parent_frame, parent_reference_id)+ if children is not None and child_execution_ids is not None:+ raise ValueError("provide child_execution_ids or children, not both")+ if children is not None:+ child_records = [child.model_copy(deep=True) for child in children]+ child_ids = [child.child_execution_id for child in child_records]+ if len(set(child_ids)) != len(child_ids):+ raise ValueError("child execution ids must be unique")+ else:+ if child_execution_ids is None:+ raise ValueError("child dependency requires child execution ids")+ ids = list(child_execution_ids)+ self._check_count(len(ids))+ if len(set(ids)) != len(ids):+ raise ValueError("child execution ids must be unique")+ if child_frames is not None and len(child_frames) != len(ids):+ raise ValueError("child frame count must match child count")+ if child_graphs is not None and len(child_graphs) != len(ids):+ raise ValueError("child graph count must match child count")+ if child_inputs is not None and len(child_inputs) != len(ids):+ raise ValueError("child input count must match child count")+ child_records = []+ newly_issued_ids: set[str] = set()+ try:+ for index, child_id in enumerate(ids):+ with self._lock:+ was_issued = child_id in self._issued_children+ child_records.append(+ self.create_child(+ child_id,+ graph=child_graphs[index] if child_graphs is not None else graph,+ inputs=child_inputs[index] if child_inputs is not None else inputs,+ child_frame=child_frames[index] if child_frames is not None else None,+ ).model_copy(update={"enqueue_index": index})+ )+ if not was_issued:+ newly_issued_ids.add(child_id)+ except Exception:+ with self._lock:+ for child_id in newly_issued_ids:+ self._issued_children.pop(child_id, None)+ raise+ self._check_count(len(child_records))+ expected_parent = self.parent_execution_id+ expected_frame = self.parent_frame+ expected_reference = self.parent_reference_id+ for index, child in enumerate(child_records):+ if child.parent_execution_id != expected_parent:+ raise ValueError("child parent execution identity does not match capability")+ if child.parent_frame != expected_frame:+ raise ValueError("child parent frame does not match capability")+ if child.parent_reference_id != expected_reference:+ raise ValueError("child parent reference identity does not match capability")+ if child.capability_id not in (None, self.capability_id):+ raise ValueError("child capability identity does not match capability")+ if child.depth != self.depth + 1:+ raise ValueError("child depth does not match capability")+ if (+ len(child.child_frame) <= len(self.parent_frame)+ or child.child_frame[: len(self.parent_frame)] != self.parent_frame+ ):+ raise ValueError("child frame must descend from the authorized parent frame")+ child_records[index] = child.model_copy(+ update={"enqueue_index": index, "capability_id": self.capability_id}+ )+ with self._lock:+ new_children = {+ child.child_execution_id: child+ for child in child_records+ if child.child_execution_id not in self._issued_children+ }+ for child in child_records:+ existing = self._issued_children.get(child.child_execution_id)+ if existing is not None and existing.model_copy(update={"enqueue_index": child.enqueue_index}) != child:+ raise ValueError("child execution id was already issued with different data")+ self._check_available(len(new_children))+ for child_id, child in new_children.items():+ self._issued_children[child_id] = child+ return ChildDependencyRecord(+ dependency_id=dependency_id or str(uuid4()),+ parent_execution_id=expected_parent,+ parent_frame=expected_frame,+ parent_reference_id=expected_reference,+ children=child_records,+ failure_policy=failure_policy or self.failure_policy,+ cancellation_policy=cancellation_policy or self.cancellation_policy,+ )++ create_child_dependency = create_dependency+ spawn_children = create_dependency+++class ChildDependencyRecord(_ChildModel):+ """All-of parent dependency with durable enqueue and terminal state."""++ dependency_id: str = Field(min_length=1)+ parent_execution_id: str = Field(min_length=1)+ parent_frame: tuple[int | str, ...] = Field(default_factory=tuple)+ parent_reference_id: str | None = Field(default=None, min_length=1)+ children: list[ChildExecutionRecord] = Field(default_factory=list)+ completions: dict[str, ChildCompletion] = Field(default_factory=dict)+ status: ChildDependencyStatus = "waiting"+ failure_policy: ChildFailurePolicy = "fail_parent"+ cancellation_policy: ChildCancellationPolicy = "cancel_parent"+ error_message: str | None = None+ output_keys: tuple[str, ...] | None = None+ terminal_transition_count: int = Field(default=0, ge=0)+ sealed: bool = True++ _lock: Any = PrivateAttr(default_factory=threading.RLock)++ _validate_parent_frame = field_validator("parent_frame", mode="before")(_frame)++ @field_validator("dependency_id", "parent_execution_id")+ @classmethod+ def _validate_ids(cls, value: str) -> str:+ return _id(value, "dependency identity")++ @field_validator("parent_reference_id")+ @classmethod+ def _validate_reference_id(cls, value: str | None) -> str | None:+ return None if value is None else _id(value, "parent reference id")++ @model_validator(mode="before")+ @classmethod+ def _accept_child_id_list(cls, value: Any) -> Any:+ if not isinstance(value, dict):+ return value+ data = dict(value)+ child_ids = data.pop("child_execution_ids", None)+ if child_ids is None:+ return data+ if data.get("children") is not None:+ raise ValueError("provide child_execution_ids or children, not both")+ parent_id = data.get("parent_execution_id")+ parent_frame = data.get("parent_frame", ())+ parent_reference = data.get("parent_reference_id")+ data["children"] = [+ {+ "child_execution_id": child_id,+ "parent_execution_id": parent_id,+ "parent_frame": parent_frame,+ "parent_reference_id": parent_reference,+ "child_frame": (*_frame(parent_frame), child_id),+ "enqueue_index": index,+ }+ for index, child_id in enumerate(child_ids)+ ]+ return data++ @model_validator(mode="after")+ def _validate_relationship(self) -> "ChildDependencyRecord":+ if not self.children:+ raise ValueError("child dependency must contain at least one child")+ child_ids = [child.child_execution_id for child in self.children]+ if len(set(child_ids)) != len(child_ids):+ raise ValueError("child execution ids must be unique")+ if any(child.parent_execution_id != self.parent_execution_id for child in self.children):+ raise ValueError("child parent execution identity does not match dependency")+ if any(child.parent_frame != self.parent_frame for child in self.children):+ raise ValueError("child parent frame does not match dependency")+ if any(child.parent_reference_id != self.parent_reference_id for child in self.children):+ raise ValueError("child parent reference identity does not match dependency")+ if any(+ len(child.child_frame) <= len(self.parent_frame)+ or child.child_frame[: len(self.parent_frame)] != self.parent_frame+ for child in self.children+ ):+ raise ValueError("child frame must descend from the parent frame")+ child_map = {child.child_execution_id: child for child in self.children}+ for child_id, completion in self.completions.items():+ if child_id not in child_map or completion.child_execution_id != child_id:+ raise ValueError("completion child identity does not match dependency")+ self._check_completion_identity(child_map[child_id], completion)+ if self.output_keys is not None:+ for completion in self.completions.values():+ if completion.status == "completed" and tuple(sorted(completion.outputs)) != self.output_keys:+ raise ValueError("child completions returned different output keys")+ if self.terminal_transition_count > 1:+ raise ValueError("terminal transition count must be exactly once")+ if self.status == "completed":+ if len(self.completions) != len(self.children) or any(+ completion.status != "completed" for completion in self.completions.values()+ ):+ raise ValueError("completed dependency must contain completed results for every child")+ if self.status == "failed" and not self.error_message:+ raise ValueError("failed dependency requires an error message")+ if self.status in _TERMINAL_STATES and self.terminal_transition_count != 1:+ raise ValueError("terminal dependency must have exactly one terminal transition")+ if self.status not in _TERMINAL_STATES and self.terminal_transition_count != 0:+ raise ValueError("active dependency cannot have a terminal transition")+ for child_id, completion in self.completions.items():+ if child_map[child_id].state != completion.status:+ raise ValueError("child state does not match its completion")+ return self++ @property+ def child_execution_ids(self) -> list[str]:+ return [child.child_execution_id for child in self.children]++ @property+ def enqueue_order(self) -> list[str]:+ return self.child_execution_ids++ @property+ def completed_child_execution_ids(self) -> list[str]:+ return [child_id for child_id in self.child_execution_ids if child_id in self.completions]++ @property+ def expected_child_count(self) -> int:+ return len(self.children)++ @property+ def child_outputs(self) -> dict[str, dict[str, Any]]:+ return {child_id: self.completions[child_id].outputs for child_id in self.completed_child_execution_ids}++ @property+ def aggregated_outputs(self) -> dict[str, list[Any]]:+ output_keys: list[str] = []+ for child_id in self.child_execution_ids:+ completion = self.completions.get(child_id)+ if completion is None:+ continue+ for key in completion.outputs:+ if key not in output_keys:+ output_keys.append(key)+ return {+ key: [+ self.completions[child_id].outputs[key]+ for child_id in self.completed_child_execution_ids+ if key in self.completions[child_id].outputs+ ]+ for key in output_keys+ }++ def _child(self, child_execution_id: str) -> ChildExecutionRecord:+ for child in self.children:+ if child.child_execution_id == child_execution_id:+ return child+ raise ValueError(f"child execution '{child_execution_id}' does not belong to dependency")++ def _check_completion_identity(self, child: ChildExecutionRecord, completion: ChildCompletion) -> None:+ if completion.parent_execution_id != self.parent_execution_id:+ raise ValueError("completion parent execution identity does not match dependency")+ if completion.parent_frame != self.parent_frame:+ raise ValueError("completion parent frame does not match dependency")+ if completion.parent_reference_id != self.parent_reference_id:+ raise ValueError("completion parent reference identity does not match dependency")+ if completion.child_frame != child.child_frame:+ raise ValueError("completion child frame does not match dependency")++ def _check_output_shape(self, outputs: dict[str, Any]) -> None:+ if self.output_keys is not None and tuple(sorted(outputs)) != self.output_keys:+ raise ValueError("child completions returned different output keys")++ def _update_for_terminal(self, status: ChildTerminalStatus, message: str | None) -> ChildDependencyUpdate:+ parent_action: Literal["failed", "canceled"] | None = None+ cancel_child_ids: list[str] = []+ if status == "failed":+ if self.failure_policy in ("fail_parent", "cancel_siblings"):+ parent_action = "failed"+ if self.failure_policy == "cancel_siblings":+ cancel_child_ids = [+ child_id for child_id in self.child_execution_ids if child_id not in self.completions+ ]+ elif status == "canceled":+ if self.cancellation_policy in ("cancel_parent", "cancel_siblings"):+ parent_action = "canceled"+ if self.cancellation_policy == "cancel_siblings":+ cancel_child_ids = [+ child_id for child_id in self.child_execution_ids if child_id not in self.completions+ ]+ return ChildDependencyUpdate(+ changed=True,+ terminal=True,+ status=self.status,+ aggregated_outputs=self.aggregated_outputs,+ parent_action=parent_action,+ cancel_child_ids=cancel_child_ids,+ error_message=message,+ )++ def _result(+ self, *, changed: bool, parent_action: Literal["failed", "canceled"] | None = None+ ) -> ChildDependencyUpdate:+ return ChildDependencyUpdate(+ changed=changed,+ terminal=self.status in _TERMINAL_STATES,+ status=self.status,+ aggregated_outputs=self.aggregated_outputs,+ parent_action=parent_action,+ cancel_child_ids=[],+ error_message=self.error_message,+ )++ def transition_terminal(self, status: ChildTerminalStatus, message: str | None = None) -> bool:+ with self._lock:+ if self.status in _TERMINAL_STATES:+ if self.status != status or self.error_message != message:+ raise ValueError("dependency already has a different terminal state")+ return False+ if status == "failed" and not message:+ raise ValueError("failed dependency requires an error message")+ if status == "completed" and len(self.completions) != len(self.children):+ raise ValueError("completed dependency must contain every child result")+ self.status = status+ self.error_message = message+ self.terminal_transition_count += 1+ return True++ def _record_completion(self, completion: ChildCompletion) -> ChildDependencyUpdate:+ child = self._child(completion.child_execution_id)+ self._check_completion_identity(child, completion)+ existing = self.completions.get(completion.child_execution_id)+ if existing is not None:+ if existing == completion:+ return self._result(changed=False)+ raise ValueError("child already has a different terminal completion")+ if self.status in _TERMINAL_STATES:+ return self._result(changed=False)+ if completion.status == "completed":+ self._check_output_shape(completion.outputs)+ self.completions[completion.child_execution_id] = completion+ if self.output_keys is None and completion.status == "completed":+ self.output_keys = tuple(sorted(completion.outputs))+ child.state = completion.status+ self.status = "running"+ if completion.status == "failed" and self.failure_policy != "continue":+ self.transition_terminal("failed", completion.error_message)+ return self._update_for_terminal("failed", completion.error_message)+ if completion.status == "canceled" and self.cancellation_policy != "continue":+ self.transition_terminal("canceled", completion.error_message)+ return self._update_for_terminal("canceled", completion.error_message)+ if len(self.completions) == len(self.children):+ final_status: ChildTerminalStatus = "completed"+ final_message: str | None = None+ if any(item.status == "failed" for item in self.completions.values()):+ final_status = "failed"+ final_message = next(+ (+ item.error_message+ for item in self.completions.values()+ if item.status == "failed" and item.error_message+ ),+ "child failed",+ )+ elif any(item.status == "canceled" for item in self.completions.values()):+ final_status = "canceled"+ final_message = next(+ (+ item.error_message+ for item in self.completions.values()+ if item.status == "canceled" and item.error_message+ ),+ "child canceled",+ )+ self.transition_terminal(final_status, final_message)+ return self._update_for_terminal(final_status, final_message)+ return self._result(changed=True)++ def record_completion(self, completion: ChildCompletion) -> ChildDependencyUpdate:+ """Record one terminal child event atomically and idempotently."""++ with self._lock:+ return self._record_completion(completion)++ def _make_completion(+ self,+ child_execution_id: str,+ status: ChildTerminalStatus,+ outputs: dict[str, Any] | None,+ message: str | None,+ child_frame: Sequence[int | str] | None,+ ) -> ChildCompletion:+ child = self._child(child_execution_id)+ return ChildCompletion(+ child_execution_id=child_execution_id,+ parent_execution_id=self.parent_execution_id,+ parent_frame=self.parent_frame,+ parent_reference_id=self.parent_reference_id,+ child_frame=child.child_frame if child_frame is None else child_frame,+ status=status,+ outputs={} if outputs is None else outputs,+ error_message=message,+ )++ def complete_child(+ self,+ 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:+ self._check_identity_arguments(parent_execution_id, parent_frame, parent_reference_id)+ return self.record_completion(+ self._make_completion(child_execution_id, "completed", outputs, None, child_frame)+ )++ def fail_child(+ self,+ child_execution_id: str,+ message: str,+ *,+ 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:+ self._check_identity_arguments(parent_execution_id, parent_frame, parent_reference_id)+ return self.record_completion(self._make_completion(child_execution_id, "failed", None, message, child_frame))++ def cancel_child(+ self,+ child_execution_id: str,+ message: str = "child canceled",+ *,+ 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:+ self._check_identity_arguments(parent_execution_id, parent_frame, parent_reference_id)+ return self.record_completion(self._make_completion(child_execution_id, "canceled", None, message, child_frame))++ def _check_identity_arguments(+ self,+ parent_execution_id: str | None,+ parent_frame: Sequence[int | str] | None,+ parent_reference_id: str | None,+ ) -> None:+ if parent_execution_id is not None and parent_execution_id != self.parent_execution_id:+ raise ValueError("parent execution identity does not match dependency")+ if parent_frame is not None and _frame(parent_frame) != self.parent_frame:+ raise ValueError("parent frame does not match dependency")+ if parent_reference_id is not None and parent_reference_id != self.parent_reference_id:+ raise ValueError("parent reference identity does not match dependency")++ def __eq__(self, other: object) -> bool:+ if not isinstance(other, ChildDependencyRecord):+ return NotImplemented+ return 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/invokeai/app/services/shared/execution_engine/primitives.py b/invokeai/app/services/shared/execution_engine/primitives.pynew file mode 100644index 0000000000..e9134b4f63--- /dev/null+++ b/invokeai/app/services/shared/execution_engine/primitives.py@@ -0,0 +1,532 @@+"""Typed, frame-scoped execution records.++These models are internal runtime records. They deliberately do not reuse or+extend public graph/effect schema models. State-changing methods validate all+inputs before one locked mutation, and repeated identical terminal inputs are+safe to retry.+"""++from __future__ import annotations++import threading+from typing import Any, Generic, Literal, TypeAlias, TypeVar, cast++from pydantic import (+ AliasChoices,+ BaseModel,+ ConfigDict,+ Field,+ PrivateAttr,+ TypeAdapter,+ field_validator,+ model_validator,+)+from pydantic_core import PydanticSerializationError++_JSON_ADAPTER = TypeAdapter(Any)+_MISSING = object()+FramePart = int | str+T = TypeVar("T")+++def _validate_json_value(value: Any) -> Any:+ try:+ _JSON_ADAPTER.dump_python(value, mode="json", warnings="error")+ except (PydanticSerializationError, TypeError, ValueError) as exc:+ raise ValueError("must be JSON-serializable") from exc+ return value+++def _validate_name(value: str) -> str:+ if not value.strip():+ raise ValueError("must not be blank")+ return value+++class _InternalModel(BaseModel):+ """Strict base for private runtime records."""++ model_config = ConfigDict(extra="forbid", validate_assignment=True)++ def __eq__(self, other: object) -> bool:+ """Compare durable fields, excluding process-local synchronization locks."""++ if not isinstance(other, type(self)):+ return NotImplemented+ return self.model_dump(mode="python") == other.model_dump(mode="python")+++class ExecutionFrame(_InternalModel):+ """Complete identity of one execution frame.++ Iteration path alone is not identity: state, generated frame ID, and call+ depth remain part of the scope key.+ """++ state_id: str = Field(+ validation_alias=AliasChoices("state_id", "execution_id", "owner_id"),+ description="Owning graph execution state identifier.",+ )+ frame_id: str = Field(description="Stable identifier for this frame.")+ iteration_path: tuple[FramePart, ...] = Field(+ default_factory=tuple,+ validation_alias=AliasChoices("iteration_path", "path", "frame_path"),+ description="Nested iteration coordinates.",+ )+ workflow_call_depth: int = Field(+ default=0,+ ge=0,+ validation_alias=AliasChoices("workflow_call_depth", "call_depth", "depth"),+ description="Nested workflow-call depth.",+ )++ model_config = ConfigDict(extra="forbid", frozen=True)++ _validate_state_id = field_validator("state_id", "frame_id")(_validate_name)++ @field_validator("iteration_path")+ @classmethod+ def _validate_iteration_path(cls, value: tuple[FramePart, ...]) -> tuple[FramePart, ...]:+ for part in value:+ if isinstance(part, bool) or not isinstance(part, (int, str)):+ raise ValueError("frame path values must be integers or strings")+ if isinstance(part, int) and part < 0:+ raise ValueError("frame path integers must be non-negative")+ if isinstance(part, str) and not part.strip():+ raise ValueError("frame path strings must not be blank")+ return value++ @property+ def execution_id(self) -> str:+ return self.state_id++ @property+ def path(self) -> tuple[FramePart, ...]:+ return self.iteration_path++ @property+ def identity(self) -> tuple[str, str, tuple[FramePart, ...], int]:+ return (self.state_id, self.frame_id, self.iteration_path, self.workflow_call_depth)++ @property+ def key(self) -> tuple[str, str, tuple[FramePart, ...], int]:+ return self.identity++ def __hash__(self) -> int:+ return hash(self.identity)+++FrameIdentity = ExecutionFrame+ExecutionFrameIdentity = ExecutionFrame+++ActivationStatus = Literal["pending", "resolved"]+++class ActivationGate(_InternalModel):+ """One immutable-in-meaning branch decision per owner and frame.++ ``resolve`` is idempotent for the same branch. A different branch after+ resolution is rejected, including when it arrives from a retry.+ """++ gate_id: str = Field(min_length=1, description="Stable gate identifier.")+ owner_id: str = Field(+ validation_alias=AliasChoices("owner_id", "owner"),+ description="Node or runtime owner of this gate.",+ )+ frame: ExecutionFrame+ branches: tuple[str, ...] = Field(+ min_length=1,+ validation_alias=AliasChoices("branches", "branch_ids"),+ description="Allowed branch identifiers.",+ )+ status: ActivationStatus = "pending"+ selected_branch: str | None = None++ _lock: Any = PrivateAttr(default_factory=threading.RLock)++ _validate_gate_id = field_validator("gate_id", "owner_id")(_validate_name)++ @field_validator("branches")+ @classmethod+ def _validate_branches(cls, value: tuple[str, ...]) -> tuple[str, ...]:+ if len(set(value)) != len(value):+ raise ValueError("branches must be unique")+ for branch in value:+ _validate_name(branch)+ return value++ @field_validator("selected_branch")+ @classmethod+ def _validate_selected_branch(cls, value: str | None) -> str | None:+ return None if value is None else _validate_name(value)++ @model_validator(mode="after")+ def _validate_resolution(self) -> "ActivationGate":+ if self.status == "pending" and self.selected_branch is not None:+ raise ValueError("pending gate cannot have a selected branch")+ if self.status == "resolved":+ if self.selected_branch is None:+ raise ValueError("resolved gate requires a selected branch")+ if self.selected_branch not in self.branches:+ raise ValueError("selected branch must be one of branches")+ return self++ @property+ def resolved(self) -> bool:+ return self.status == "resolved"++ @property+ def branch(self) -> str | None:+ return self.selected_branch++ def assert_scope(self, owner_id: str, frame: ExecutionFrame) -> None:+ if owner_id != self.owner_id:+ raise ValueError("activation gate owner does not match")+ if frame != self.frame:+ raise ValueError("activation gate frame does not match")++ def resolve(self, branch: str) -> bool:+ """Resolve gate once; return whether state changed."""++ _validate_name(branch)+ with self._lock:+ if branch not in self.branches:+ raise ValueError(f"unknown activation branch: {branch}")+ if self.selected_branch is None:+ object.__setattr__(self, "selected_branch", branch)+ object.__setattr__(self, "status", "resolved")+ return True+ if self.selected_branch == branch:+ return False+ raise ValueError("activation gate is already resolved")++ resolve_once = resolve++ def is_active(+ self,+ branch: str,+ *,+ owner_id: str | None = None,+ frame: ExecutionFrame | None = None,+ ) -> bool:+ with self._lock:+ if owner_id is not None and frame is not None:+ self.assert_scope(owner_id, frame)+ elif owner_id is not None:+ if owner_id != self.owner_id:+ raise ValueError("activation gate owner does not match")+ elif frame is not None and frame != self.frame:+ raise ValueError("activation gate frame does not match")+ return self.selected_branch == branch+++class StreamData(_InternalModel, Generic[T]):+ """One ordered stream data item; ``None`` is a valid value."""++ kind: Literal["data"] = Field(+ default="data",+ validation_alias=AliasChoices("kind", "token_kind", "type"),+ )+ sequence: int = Field(ge=0)+ value: T++ @model_validator(mode="after")+ def _validate_value(self) -> "StreamData[T]":+ _validate_json_value(self.value)+ return self+++class StreamEnd(_InternalModel):+ """End marker at sequence equal to number of data items."""++ kind: Literal["stream_end"] = Field(+ default="stream_end",+ validation_alias=AliasChoices("kind", "token_kind", "type"),+ )+ sequence: int = Field(default=0, ge=0)+++StreamEvent: TypeAlias = StreamData[T] | StreamEnd+++class StreamBuffer(_InternalModel, Generic[T]):+ """Atomic ordered buffer for one owner/frame stream.++ Data sequences start at zero. End sequence equals data count, allowing an+ empty stream to close at sequence zero. Exact event retries are no-ops;+ conflicting duplicate sequences and gaps are rejected.+ """++ stream_id: str = Field(min_length=1)+ owner_id: str = Field(+ validation_alias=AliasChoices("owner_id", "owner"),+ description="Node or runtime owner of this stream.",+ )+ frame: ExecutionFrame+ events: tuple[StreamData[T] | StreamEnd, ...] = Field(default_factory=tuple)+ next_sequence: int = Field(default=0, ge=0)+ closed: bool = False+ end_sequence: int | None = Field(default=None, ge=0)++ _lock: Any = PrivateAttr(default_factory=threading.RLock)++ _validate_stream_id = field_validator("stream_id", "owner_id")(_validate_name)++ @model_validator(mode="after")+ def _validate_buffer_state(self) -> "StreamBuffer[T]":+ expected = 0+ saw_end = False+ for event in self.events:+ if saw_end:+ raise ValueError("stream events cannot follow stream_end")+ if event.sequence != expected:+ raise ValueError("stream events must be ordered without gaps")+ if isinstance(event, StreamData):+ expected += 1+ continue+ saw_end = True+ if self.end_sequence != event.sequence:+ raise ValueError("stream end sequence does not match buffer")+ if self.next_sequence != expected:+ raise ValueError("buffer next sequence does not match events")+ if self.closed != saw_end:+ raise ValueError("buffer closed state does not match stream_end")+ if not saw_end and self.end_sequence is not None:+ raise ValueError("open buffer cannot have an end sequence")+ return self++ @property+ def values(self) -> tuple[T, ...]:+ with self._lock:+ return tuple(cast(StreamData[T], event).value for event in self.events if isinstance(event, StreamData))++ @property+ def data(self) -> tuple[T, ...]:+ return self.values++ @property+ def expected_sequence(self) -> int:+ return self.next_sequence++ def assert_scope(self, owner_id: str, frame: ExecutionFrame) -> None:+ if owner_id != self.owner_id:+ raise ValueError("stream buffer owner does not match")+ if frame != self.frame:+ raise ValueError("stream buffer frame does not match")++ def _data_model(self) -> Any:+ generic_args = getattr(type(self), "__pydantic_generic_metadata__", {}).get("args", ())+ value_type = generic_args[0] if generic_args else Any+ return StreamData[value_type] if value_type is not Any else StreamData[Any]++ def _make_data_event(self, sequence: int, value: Any) -> StreamData[T]:+ return cast(StreamData[T], self._data_model()(sequence=sequence, value=value))++ def _coerce_event(+ self,+ event: StreamData[T] | StreamEnd | str | dict[str, Any],+ *,+ value: Any = _MISSING,+ sequence: int | None = None,+ ) -> StreamData[T] | StreamEnd:+ if isinstance(event, StreamData):+ if value is not _MISSING or sequence is not None:+ raise TypeError("event object cannot be combined with value or sequence")+ return self._make_data_event(event.sequence, event.value)+ if isinstance(event, StreamEnd):+ if value is not _MISSING or sequence is not None:+ raise TypeError("event object cannot be combined with value or sequence")+ return event+ if isinstance(event, dict):+ kind = event.get("kind", event.get("token_kind", event.get("type")))+ if kind == "data":+ return cast(StreamData[T], self._data_model().model_validate(event))+ if kind == "stream_end":+ return StreamEnd.model_validate(event)+ raise ValueError("stream event kind must be data or stream_end")+ if event not in ("data", "stream_end"):+ raise ValueError("stream event kind must be data or stream_end")+ event_sequence = self.next_sequence if sequence is None else sequence+ if event == "data":+ if value is _MISSING:+ raise ValueError("data event requires a value")+ return self._make_data_event(event_sequence, value)+ if value is not _MISSING:+ raise TypeError("stream_end event cannot have a value")+ return StreamEnd(sequence=event_sequence)++ def accept(+ self,+ event: StreamData[T] | StreamEnd | str | dict[str, Any],+ *,+ value: Any = _MISSING,+ sequence: int | None = None,+ ) -> bool:+ """Accept one event atomically; return false for exact retries."""++ with self._lock:+ candidate = self._coerce_event(event, value=value, sequence=sequence)+ existing = next((item for item in self.events if item.sequence == candidate.sequence), None)+ if existing is not None:+ if existing == candidate:+ return False+ if self.closed:+ raise ValueError("stream buffer is closed")+ if existing is not None:+ raise ValueError("duplicate stream sequence has conflicting data")+ if candidate.sequence != self.next_sequence:+ raise ValueError("stream event is out of order")++ new_events = (*self.events, candidate)+ if isinstance(candidate, StreamData):+ object.__setattr__(self, "events", new_events)+ object.__setattr__(self, "next_sequence", self.next_sequence + 1)+ else:+ object.__setattr__(self, "events", new_events)+ object.__setattr__(self, "closed", True)+ object.__setattr__(self, "end_sequence", candidate.sequence)+ return True++ def append_data(self, value: T, *, sequence: int | None = None) -> bool:+ return self.accept("data", value=value, sequence=sequence)++ add_data = append_data++ def close(self, *, sequence: int | None = None) -> bool:+ return self.accept("stream_end", sequence=sequence)++ stream_end = close++ def __eq__(self, other: object) -> bool:+ if not isinstance(other, StreamBuffer):+ return NotImplemented+ return self.model_dump(mode="json") == other.model_dump(mode="json")+++ContinuationStatus = Literal["pending", "waiting", "running", "completed", "failed", "cancelled"]+++class ContinuationRecord(_InternalModel, Generic[T]):+ """Generic owner/frame continuation with a small durable state machine."""++ continuation_id: str = Field(+ validation_alias=AliasChoices("continuation_id", "id"),+ description="Stable continuation identifier.",+ )+ owner_id: str = Field(+ validation_alias=AliasChoices("owner_id", "owner"),+ description="Node or runtime owner of this continuation.",+ )+ frame: ExecutionFrame+ kind: str = Field(min_length=1)+ status: ContinuationStatus = "pending"+ payload: T | None = None+ result: T | None = None+ error: str | None = None++ _lock: Any = PrivateAttr(default_factory=threading.RLock)++ _validate_ids = field_validator("continuation_id", "owner_id", "kind")(_validate_name)++ @field_validator("payload", "result")+ @classmethod+ def _validate_payload_result(cls, value: T | None) -> T | None:+ return _validate_json_value(value)++ @field_validator("error")+ @classmethod+ def _validate_error(cls, value: str | None) -> str | None:+ return None if value is None else _validate_name(value)++ @model_validator(mode="after")+ def _validate_status_data(self) -> "ContinuationRecord[T]":+ if self.status in ("pending", "waiting", "running") and (self.result is not None or self.error is not None):+ raise ValueError("active continuation cannot have result or error")+ if self.status == "completed" and self.error is not None:+ raise ValueError("completed continuation cannot have error")+ if self.status == "failed" and self.error is None:+ raise ValueError("failed continuation requires error")+ return self++ @property+ def terminal(self) -> bool:+ return self.status in ("completed", "failed", "cancelled")++ def assert_scope(self, owner_id: str, frame: ExecutionFrame) -> None:+ if owner_id != self.owner_id:+ raise ValueError("continuation owner does not match")+ if frame != self.frame:+ raise ValueError("continuation frame does not match")++ def transition(+ self,+ status: ContinuationStatus,+ *,+ result: T | None = None,+ error: str | None = None,+ ) -> bool:+ """Apply valid transition atomically; return false for same-state retry."""++ if error is not None:+ _validate_name(error)+ _validate_json_value(result)+ allowed: dict[ContinuationStatus, frozenset[ContinuationStatus]] = {+ "pending": frozenset({"waiting", "running", "failed", "cancelled"}),+ "waiting": frozenset({"running", "failed", "cancelled"}),+ "running": frozenset({"completed", "failed", "cancelled"}),+ "completed": frozenset(),+ "failed": frozenset(),+ "cancelled": frozenset(),+ }++ with self._lock:+ if status == self.status:+ if status == "completed" and self.result != result:+ raise ValueError("completed continuation has conflicting result")+ if status == "failed" and self.error != error:+ raise ValueError("failed continuation has conflicting error")+ if status == "cancelled" and self.error != error:+ raise ValueError("cancelled continuation has conflicting error")+ return False+ if status not in allowed[self.status]:+ if self.terminal:+ raise ValueError("continuation is terminal")+ raise ValueError(f"invalid continuation transition: {self.status} to {status}")+ if status == "completed":+ if error is not None:+ raise ValueError("completed continuation cannot have error")+ elif status == "failed":+ if error is None:+ raise ValueError("failed continuation requires error")+ result = None+ elif status in ("pending", "waiting", "running"):+ result = None+ error = None+ object.__setattr__(self, "status", status)+ object.__setattr__(self, "result", result)+ object.__setattr__(self, "error", error)+ return True++ def wait(self) -> bool:+ return self.transition("waiting")++ def start(self) -> bool:+ return self.transition("running")++ resume = start++ def complete(self, result: T | None = None) -> bool:+ return self.transition("completed", result=result)++ def fail(self, error: str) -> bool:+ return self.transition("failed", error=error)++ def cancel(self, reason: str | None = None) -> bool:+ return self.transition("cancelled", error=reason)++ def __eq__(self, other: object) -> bool:+ if not isinstance(other, ContinuationRecord):+ return NotImplemented+ return self.model_dump(mode="json") == other.model_dump(mode="json")diff --git a/invokeai/app/services/shared/execution_engine/runtime.py b/invokeai/app/services/shared/execution_engine/runtime.pynew file mode 100644index 0000000000..5de83bf10b--- /dev/null+++ b/invokeai/app/services/shared/execution_engine/runtime.py@@ -0,0 +1,114 @@+"""State-local registries for generic execution primitives.++The registries are deliberately independent of ``GraphExecutionState``. The+state owns the compatibility adapter and persists the resulting records using+its existing runtime snapshot fields; this module owns identity and lifecycle+invariants.+"""++from __future__ import annotations++from typing import Any++from pydantic import BaseModel, ConfigDict, Field++from invokeai.app.services.shared.execution_engine.primitives import (+ ActivationGate,+ ContinuationRecord,+ ExecutionFrame,+ StreamBuffer,+)+++class ExecutionEngineRuntime(BaseModel):+ """Typed, frame-scoped runtime records used by compatibility adapters."""++ model_config = ConfigDict(extra="forbid")++ gates: dict[str, ActivationGate] = Field(default_factory=dict)+ streams: dict[str, StreamBuffer[Any]] = Field(default_factory=dict)+ continuations: dict[str, ContinuationRecord[Any]] = Field(default_factory=dict)++ def register_gate(+ self,+ gate_id: str,+ owner_id: str,+ frame: ExecutionFrame,+ branches: tuple[str, ...],+ ) -> ActivationGate:+ existing = self.gates.get(gate_id)+ if existing is not None:+ if existing.owner_id != owner_id or existing.frame != frame or existing.branches != branches:+ raise ValueError(f"activation gate identity conflict: {gate_id}")+ return existing+ gate = ActivationGate(gate_id=gate_id, owner_id=owner_id, frame=frame, branches=branches)+ self.gates[gate_id] = gate+ return gate++ def get_gate(self, gate_id: str) -> ActivationGate:+ try:+ return self.gates[gate_id]+ except KeyError as exc:+ raise KeyError(f"activation gate not registered: {gate_id}") from exc++ def replace_gate(self, gate: ActivationGate) -> None:+ self.gates[gate.gate_id] = gate++ def remove_gate(self, gate_id: str) -> None:+ self.gates.pop(gate_id, None)++ def resolve_gate(self, gate_id: str, owner_id: str, frame: ExecutionFrame, branch: str) -> bool:+ gate = self.get_gate(gate_id)+ gate.assert_scope(owner_id, frame)+ return gate.resolve(branch)++ def get_or_create_stream(self, stream_id: str, owner_id: str, frame: ExecutionFrame) -> StreamBuffer[Any]:+ existing = self.streams.get(stream_id)+ if existing is not None:+ existing.assert_scope(owner_id, frame)+ return existing+ stream = StreamBuffer[Any](stream_id=stream_id, owner_id=owner_id, frame=frame)+ self.streams[stream_id] = stream+ return stream++ def get_stream(self, stream_id: str) -> StreamBuffer[Any]:+ try:+ return self.streams[stream_id]+ except KeyError as exc:+ raise KeyError(f"stream not registered: {stream_id}") from exc++ def replace_stream(self, stream: StreamBuffer[Any]) -> None:+ self.streams[stream.stream_id] = stream++ def remove_stream(self, stream_id: str) -> None:+ self.streams.pop(stream_id, None)++ def register_continuation(+ self, continuation_id: str, owner_id: str, frame: ExecutionFrame, kind: str+ ) -> ContinuationRecord[Any]:+ existing = self.continuations.get(continuation_id)+ if existing is not None:+ existing.assert_scope(owner_id, frame)+ if existing.kind != kind:+ raise ValueError(f"continuation identity conflict: {continuation_id}")+ return existing+ continuation = ContinuationRecord[Any](+ continuation_id=continuation_id,+ owner_id=owner_id,+ frame=frame,+ kind=kind,+ )+ self.continuations[continuation_id] = continuation+ return continuation++ def replace_continuation(self, continuation: ContinuationRecord[Any]) -> None:+ self.continuations[continuation.continuation_id] = continuation++ def remove_continuation(self, continuation_id: str) -> None:+ self.continuations.pop(continuation_id, None)++ def get_continuation(self, continuation_id: str) -> ContinuationRecord[Any]:+ try:+ return self.continuations[continuation_id]+ except KeyError as exc:+ raise KeyError(f"continuation not registered: {continuation_id}") from excdiff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 6d4ca963d3..01e75c1310 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -60,6 +60,21 @@ from invokeai.app.invocations.loops import (ForReturnInvocationOutput,LoopState,)+from invokeai.app.services.shared.execution_engine.child import (+ ChildDependencyRecord,+ ChildDependencyUpdate,+ ChildExecutionCapability,+)+from invokeai.app.services.shared.execution_engine.primitives import (+ ActivationGate,+ ContinuationRecord,+ StreamBuffer,+ StreamData,+)+from invokeai.app.services.shared.execution_engine.primitives import (+ ExecutionFrame as EngineExecutionFrame,+)+from invokeai.app.services.shared.execution_engine.runtime import ExecutionEngineRuntimefrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.app.util.misc import uuid_string@@ -356,7 +371,7 @@ class _IfBranchScheduler:matching_prepared_if_ids = self._get_matching_prepared_if_ids(if_node_id, iteration_path)if not matching_prepared_if_ids:return True- return not all(pid in self._state._resolved_if_exec_branches for pid in matching_prepared_if_ids)+ return not all(self._state._activation_gate(pid).resolved for pid in matching_prepared_if_ids)def _apply_condition_inputs(self, exec_node_id: str, node: IfInvocation) -> bool:return self._state._apply_if_condition_inputs(exec_node_id, node)@@ -454,7 +469,25 @@ class _IfBranchScheduler:returnselected_field, unselected_field = self._get_selected_branch_fields(node)+ self._state._resolve_activation_gate(exec_node_id, selected_field)+ # Compatibility cache for old snapshots and callers. The typed gate is+ # the authority for new runtime decisions.self._state._tx_set_mapping(self._state._resolved_if_exec_branches, exec_node_id, selected_field)+ execution_ref = self._state._expected_execution_ref(exec_node_id)+ activation_token_id = f"{execution_ref.reference_id}:activation:{selected_field}"+ self._state._tx_set_mapping(+ self._state.execution_tokens,+ activation_token_id,+ ExecutionToken(+ token_id=activation_token_id,+ reference_id=execution_ref.reference_id,+ owner_node_id=exec_node_id,+ port=selected_field,+ frame=execution_ref.frame,+ value=selected_field,+ token_kind="activation",+ ),+ )source_if_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)exclusive_sources = self.get_branch_exclusive_sources(source_if_node_id)@@ -1101,7 +1134,7 @@ class _ExecutionMaterializer:source_iterate_id, iterate_input_map, iteration_path=outer_iteration_path)if not inner_prepared_ids:- self._mark_source_node_empty(source_iterate_id)+ self._mark_source_node_empty(source_iterate_id, outer_iteration_path)for inner_prepared_id in inner_prepared_ids:inner_iteration_path = self._state._get_iteration_path(inner_prepared_id)@@ -1139,7 +1172,7 @@ class _ExecutionMaterializer:if source_node_id in {source_iterate_id, source_collect_id, source_return_id}:continueif nx.has_path(graph, source_iterate_id, source_node_id):- self._mark_source_node_empty(source_node_id)+ self._mark_source_node_empty(source_node_id, outer_iteration_path)collect_item_edge = self._state.graph._get_input_edges(source_collect_id, ITEM_FIELD)[0]collect_edges: list[Edge] = []@@ -1426,9 +1459,11 @@ class _ExecutionMaterializer:mappings.append(mapping)return mappings- def _mark_source_node_empty(self, source_node_id: str) -> None:+ def _mark_source_node_empty(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> None:self._state._tx_set_mapping(self._state.source_prepared_mapping, source_node_id, set())self._state._mark_source_executed(source_node_id)+ if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):+ self._state._record_empty_iterate_stream(source_node_id, iteration_path)def _index_prepared_nodes_by_iteration_path(self, prepared_nodes: set[str], input_edges: list[Edge]@@ -1787,6 +1822,15 @@ class _ExecutionScheduler:self._state._set_prepared_exec_state(exec_node_id, "executed")self._state._tx_add_set(self._state.executed, exec_node_id)self._state._tx_set_mapping(self._state.results, exec_node_id, output)+ # Keep the generic stream ledger in sync while the materializer remains+ # the compatibility authority for runtime node creation.+ if isinstance(self._state.execution_graph.nodes.get(exec_node_id), IterateInvocation):+ self._state._record_iterate_stream(exec_node_id, output)+ if isinstance(self._state.execution_graph.nodes.get(exec_node_id), ForInvocation):+ for_node = self._state.execution_graph.nodes[exec_node_id]+ assert isinstance(for_node, ForInvocation)+ if for_node.index >= 0:+ self._state._for_continuation(exec_node_id)node = self._state.execution_graph.nodes[exec_node_id]if isinstance(node, (IterateInvocation, CollectInvocation)):self._state._tx_set_attr(node, "collection", [])@@ -1893,6 +1937,8 @@ class _ExecutionScheduler:if not isinstance(for_node, ForInvocation):return None+ self._state._complete_for_continuation(for_exec_node_id, output.model_dump(mode="json"))+registry = self._state._prepared_registry()source_for_id = registry.get_source_node_id(for_exec_node_id)source_return_id = registry.get_source_node_id(exec_node_id)@@ -2201,7 +2247,39 @@ class _ExecutionRuntime:output_collection.extend(source_value)else:output_collection.append(source_value)- output_collection.extend(self._get_copied_result_value(edge) for edge in item_edges)+ item_values: list[tuple[tuple[Any, ...], str, Any]] = []+ consumed_streams: set[str] = set()+ for edge in item_edges:+ stream_info = self._state._stream_for_iterate_edge(edge)+ if stream_info is None:+ item_values.append(+ (+ (*self.get_iteration_path(edge.source.node_id), 0),+ edge.source.node_id,+ self._get_copied_result_value(edge),+ )+ )+ continue+ stream_id, parent_path = stream_info+ stream = self._state._generic_runtime().streams.get(stream_id)+ if stream is None or not stream.closed:+ item_values.append(+ (+ (*self.get_iteration_path(edge.source.node_id), 0),+ edge.source.node_id,+ self._get_copied_result_value(edge),+ )+ )+ continue+ if stream_id in consumed_streams:+ continue+ consumed_streams.add(stream_id)+ item_values.extend(+ ((*parent_path, sequence), edge.source.node_id, copydeep(value))+ for sequence, value in enumerate(stream.values)+ )+ item_values.sort(key=lambda item: (item[0], item[1]))+ output_collection.extend(value for _path, _source_id, value in item_values)return output_collectiondef _set_node_inputs(@@ -4095,6 +4173,8 @@ class GraphExecutionState(BaseModel):_completed_source_ids_cache: Optional[set[str]] = PrivateAttr(default=None)_for_source_by_return_id: Optional[dict[str, str]] = PrivateAttr(default=None)_apply_transaction: Optional[_ApplyTransaction] = PrivateAttr(default=None)+ _generic_execution_runtime: Optional[ExecutionEngineRuntime] = PrivateAttr(default=None)+ _generic_child_dependencies: dict[str, ChildDependencyRecord] = PrivateAttr(default_factory=dict)def _tx_record_once(self, key: tuple[Any, ...], undo: Callable[[], None]) -> None:if self._apply_transaction is not None:@@ -4298,6 +4378,218 @@ class GraphExecutionState(BaseModel):self._execution_runtime = _ExecutionRuntime(self)return self._execution_runtime+ def _generic_runtime(self) -> ExecutionEngineRuntime:+ """Return the private typed runtime used by legacy-control adapters."""++ if self._generic_execution_runtime is None:+ self._generic_execution_runtime = ExecutionEngineRuntime()+ return self._generic_execution_runtime++ def _engine_frame(self, iteration_path: tuple[int, ...]) -> EngineExecutionFrame:+ frame_id = f"{self.id}:{len(self.workflow_call_stack)}:{','.join(str(i) for i in iteration_path)}"+ return EngineExecutionFrame(+ state_id=self.id,+ frame_id=frame_id,+ iteration_path=iteration_path,+ workflow_call_depth=len(self.workflow_call_stack),+ )++ def _activation_gate(self, exec_node_id: str) -> ActivationGate:+ return self._generic_runtime().register_gate(+ gate_id=exec_node_id,+ owner_id=exec_node_id,+ frame=self._engine_frame(self._get_iteration_path(exec_node_id)),+ branches=("true_input", "false_input"),+ )++ def _resolve_activation_gate(self, exec_node_id: str, branch: str) -> bool:+ runtime = self._generic_runtime()+ gate = self._activation_gate(exec_node_id)+ if gate.resolved and gate.selected_branch == branch:+ return False+ previous = ActivationGate.model_validate(gate.model_dump(mode="python"))+ changed = runtime.resolve_gate(+ exec_node_id,+ exec_node_id,+ gate.frame,+ branch,+ )+ if changed:+ self._tx_record(lambda: runtime.replace_gate(previous))+ return changed++ def _iteration_stream_id(self, source_node_id: str, parent_path: tuple[int, ...]) -> str:+ path = ",".join(str(index) for index in parent_path)+ return f"{self.id}:iterate:{source_node_id}:{path}"++ def _record_iterate_stream(self, exec_node_id: str, output: BaseInvocationOutput) -> None:+ if not isinstance(output, IterateInvocationOutput):+ return+ source_node_id = self.prepared_source_mapping.get(exec_node_id)+ if source_node_id is None:+ return+ iteration_path = self._get_iteration_path(exec_node_id)+ parent_path = iteration_path[:-1] if iteration_path else ()+ stream_id = self._iteration_stream_id(source_node_id, parent_path)+ runtime = self._generic_runtime()+ stream = runtime.streams.get(stream_id)+ if stream is None:+ self._tx_record(lambda: runtime.remove_stream(stream_id))+ stream = runtime.get_or_create_stream(stream_id, source_node_id, self._engine_frame(parent_path))+ elif self._apply_transaction is not None:+ previous = StreamBuffer[Any].model_validate(stream.model_dump(mode="python"))+ self._tx_record_once(("stream", stream_id), lambda: runtime.replace_stream(previous))+ stream.accept(StreamData(sequence=output.index, value=copydeep(output.item)))+ if output.index + 1 >= output.total:+ stream.close(sequence=output.total)++ def _record_empty_iterate_stream(self, source_node_id: str, parent_path: tuple[int, ...] = ()) -> None:+ runtime = self._generic_runtime()+ stream_id = self._iteration_stream_id(source_node_id, parent_path)+ stream = runtime.streams.get(stream_id)+ if stream is None:+ self._tx_record(lambda: runtime.remove_stream(stream_id))+ stream = runtime.get_or_create_stream(stream_id, source_node_id, self._engine_frame(parent_path))+ elif stream.closed:+ return+ elif self._apply_transaction is not None:+ previous = StreamBuffer[Any].model_validate(stream.model_dump(mode="python"))+ self._tx_record_once(("stream", stream_id), lambda: runtime.replace_stream(previous))+ stream.close(sequence=stream.next_sequence)++ def _record_effect_streams(self, execution_ref: ExecutionReference, effects: Iterable[Any]) -> None:+ """Mirror generic stream effects into the private stream registry."""++ for effect in effects:+ effect_kind = self._value_from_object(effect, "kind", "effect_type", "type")+ if effect_kind not in {"emit", "close_stream"}:+ continue+ token = self._value_from_object(effect, "token")+ port = self._value_from_object(token, "field", "port", "output", "output_name")+ if not isinstance(port, str):+ continue+ stream_id = f"{self.id}:effect:{execution_ref.reference_id}:{port}"+ runtime = self._generic_runtime()+ stream = runtime.streams.get(stream_id)+ if stream is None:+ self._tx_record(lambda runtime=runtime, stream_id=stream_id: runtime.remove_stream(stream_id))+ stream = runtime.get_or_create_stream(+ stream_id,+ execution_ref.exec_node_id,+ EngineExecutionFrame(+ state_id=execution_ref.frame.state_id or self.id,+ frame_id=execution_ref.frame.frame_id or f"{self.id}:{execution_ref.exec_node_id}",+ iteration_path=execution_ref.frame.iteration_path,+ workflow_call_depth=execution_ref.frame.workflow_call_depth,+ ),+ )+ elif self._apply_transaction is not None:+ previous = StreamBuffer[Any].model_validate(stream.model_dump(mode="python"))+ self._tx_record_once(+ ("stream", stream_id),+ lambda runtime=runtime, previous=previous: runtime.replace_stream(previous),+ )++ sequence = self._value_from_object(token, "sequence")+ if sequence is None:+ sequence = stream.next_sequence+ if effect_kind == "close_stream":+ stream.close(sequence=sequence)+ continue+ if self._value_from_object(token, "token_kind") == "stream_end":+ continue+ value = self._value_from_object(effect, "value")+ if value is None:+ value = self._value_from_object(token, "value")+ stream.accept(StreamData(sequence=sequence, value=copydeep(value)))++ def _stream_for_iterate_edge(self, edge: Edge) -> tuple[str, tuple[Any, ...]] | None:+ source_node_id = self.prepared_source_mapping.get(edge.source.node_id)+ if source_node_id is None or edge.source.field != ITEM_FIELD:+ return None+ if not isinstance(self.execution_graph.nodes.get(edge.source.node_id), IterateInvocation):+ return None+ iteration_path = self._get_iteration_path(edge.source.node_id)+ parent_path = iteration_path[:-1] if iteration_path else ()+ return self._iteration_stream_id(source_node_id, parent_path), parent_path++ def _for_continuation(self, for_exec_node_id: str) -> ContinuationRecord[Any]:+ runtime = self._generic_runtime()+ continuation_id = f"{self.id}:for:{for_exec_node_id}"+ continuation = runtime.continuations.get(continuation_id)+ if continuation is None:+ self._tx_record(lambda: runtime.remove_continuation(continuation_id))+ continuation = runtime.register_continuation(+ continuation_id,+ for_exec_node_id,+ self._engine_frame(self._get_iteration_path(for_exec_node_id)),+ "for",+ )+ if continuation.status == "pending":+ previous = ContinuationRecord[Any].model_validate(continuation.model_dump(mode="python"))+ self._tx_record_once(("continuation", continuation_id), lambda: runtime.replace_continuation(previous))+ continuation.start()+ return continuation++ def _complete_for_continuation(self, for_exec_node_id: str, result: Any) -> None:+ continuation = self._for_continuation(for_exec_node_id)+ if continuation.terminal:+ return+ previous = ContinuationRecord[Any].model_validate(continuation.model_dump(mode="python"))+ self._tx_record_once(+ ("continuation-complete", continuation.continuation_id),+ lambda: self._generic_runtime().replace_continuation(previous),+ )+ continuation.complete(result)++ def _register_generic_child_dependency(self) -> ChildDependencyRecord | None:+ execution = self.waiting_workflow_call_execution+ if execution is None or not execution.child_item_ids:+ return None+ existing = self._generic_child_dependencies.get(execution.id)+ if existing is not None:+ return existing+ parent_reference_id = f"{self.id}:{execution.prepared_call_node_id}"+ capability = ChildExecutionCapability(+ parent_execution_id=self.id,+ parent_frame=(),+ parent_reference_id=parent_reference_id,+ depth=max(execution.depth - 1, 0),+ max_depth=max(self.max_workflow_call_depth, execution.depth),+ max_children=max(execution.expected_child_count, 1),+ capacity=max(execution.expected_child_count, 1),+ )+ record = capability.create_dependency(+ [str(item_id) for item_id in execution.child_item_ids],+ dependency_id=execution.id,+ )+ for child_item_id in execution.completed_child_item_ids:+ output_values = execution.child_outputs.get(child_item_id)+ if output_values is not None:+ record.complete_child(str(child_item_id), output_values)+ self._generic_child_dependencies[execution.id] = record+ return record++ def record_generic_child_completion(+ self, child_item_id: int, output_values: dict[str, Any]+ ) -> ChildDependencyUpdate | None:+ dependency = self._register_generic_child_dependency()+ if dependency is None:+ return None+ return dependency.complete_child(str(child_item_id), output_values)++ def fail_generic_child(self, child_item_id: int, error_message: str) -> ChildDependencyUpdate | None:+ dependency = self._register_generic_child_dependency()+ if dependency is None:+ return None+ return dependency.fail_child(str(child_item_id), error_message)++ def cancel_generic_child(self, child_item_id: int, error_message: str) -> ChildDependencyUpdate | None:+ dependency = self._register_generic_child_dependency()+ if dependency is None:+ return None+ return dependency.cancel_child(str(child_item_id), error_message)+def _register_prepared_exec_node(self, exec_node_id: str, source_node_id: str) -> None:self._prepared_registry().register(exec_node_id, source_node_id)self._tx_discard_set(self.executed, source_node_id)@@ -4500,6 +4792,18 @@ class GraphExecutionState(BaseModel):raise ValueError(f"{owner_name} belongs to another workflow-call depth")def _validate_execution_token(self, token: Any, execution_ref: ExecutionReference) -> None:+ token_node_id = self._value_from_object(+ token,+ "node_id",+ "invocation_id",+ "source_node_id",+ "owner_node_id",+ "exec_node_id",+ "execution_node_id",+ "prepared_node_id",+ )+ if token_node_id not in (None, "", execution_ref.exec_node_id):+ raise ValueError("Execution token is not owned by execution reference")token_reference_id = self._value_from_object(token, "reference_id", "execution_ref_id")if token_reference_id not in (None, "", execution_ref.reference_id):raise ValueError("Execution token belongs to another execution reference")@@ -4603,8 +4907,11 @@ class GraphExecutionState(BaseModel):raise ValueError("Close-stream effect requires a data output token")if token_kind != "stream_end":raise ValueError("Close-stream effect requires a stream_end token")- elif effect_kind == "emit" and self._value_from_object(token, "token_kind") == "stream_end":- raise ValueError("Emit effect cannot use a stream_end token")+ elif effect_kind == "emit":+ if token is None or token_port in (None, LOOP_LINKAGE_FIELD):+ raise ValueError("Emit effect requires a data output token")+ if self._value_from_object(token, "token_kind") == "stream_end":+ raise ValueError("Emit effect cannot use a stream_end token")owner = self._value_from_object(effect,@@ -4791,6 +5098,7 @@ class GraphExecutionState(BaseModel):object.__setattr__(self, "_apply_transaction", transaction)try:finalized_outputs = self.complete(ref.exec_node_id, output_value)+ self._record_effect_streams(ref, effect_values)ref.effect_count = effect_count if effect_count is not None else ref.effect_countself._tx_set_mapping(self.execution_refs, ref.exec_node_id, ref)for token_id, token in tokens.items():@@ -5041,10 +5349,39 @@ class GraphExecutionState(BaseModel):if not isinstance(node, IfInvocation):continue+ activation_tokens = [+ token+ for token in self.execution_tokens.values()+ if token.owner_node_id == exec_node_id and token.token_kind == "activation"+ ]+ if activation_tokens:+ expected_ref = self._expected_execution_ref(exec_node_id)+ selected_fields: set[str] = set()+ for activation_token in activation_tokens:+ selected_field = activation_token.port+ if selected_field not in ("true_input", "false_input"):+ raise ValueError(f"Invalid activation token for If execution node {exec_node_id}")+ if activation_token.reference_id != expected_ref.reference_id:+ raise ValueError(f"Activation token for If execution node {exec_node_id} has a stale reference")+ if activation_token.owner_node_id != exec_node_id:+ raise ValueError(f"Activation token for If execution node {exec_node_id} has a stale owner")+ if activation_token.value != selected_field:+ raise ValueError(f"Activation token for If execution node {exec_node_id} has a stale value")+ self._validate_execution_token(activation_token, expected_ref)+ selected_fields.add(selected_field)+ if len(selected_fields) != 1:+ raise ValueError(f"If execution node {exec_node_id} has conflicting activation tokens")+ selected_field = next(iter(selected_fields))+ self._resolve_activation_gate(exec_node_id, selected_field)+ self._resolved_if_exec_branches[exec_node_id] = selected_field+ continue+if not self._apply_if_condition_inputs(exec_node_id, node):continue- self._resolved_if_exec_branches[exec_node_id] = "true_input" if node.condition else "false_input"+ selected_field = "true_input" if node.condition else "false_input"+ self._resolve_activation_gate(exec_node_id, selected_field)+ self._resolved_if_exec_branches[exec_node_id] = selected_fielddef _rehydrate_execution_refs(self) -> None:for exec_node_id in self.prepared_source_mapping:@@ -5052,6 +5389,45 @@ class GraphExecutionState(BaseModel):effect_count = existing.effect_count if existing is not None else Noneself.execution_refs[exec_node_id] = self._expected_execution_ref(exec_node_id, effect_count=effect_count)+ def _rehydrate_generic_runtime_state(self) -> None:+ """Rebuild private stream/continuation adapters from durable results."""++ for source_node_id, source_node in self.graph.nodes.items():+ if (+ isinstance(source_node, IterateInvocation)+ and source_node_id in self.executed+ and not self.source_prepared_mapping.get(source_node_id)+ ):+ self._record_empty_iterate_stream(source_node_id)++ iterate_results: list[tuple[str, IterateInvocationOutput]] = []+ for exec_node_id, output in self.results.items():+ if isinstance(output, IterateInvocationOutput):+ iterate_results.append((exec_node_id, output))+ iterate_results.sort(key=lambda item: (self._get_iteration_path(item[0]), item[1].index, item[0]))+ for exec_node_id, output in iterate_results:+ self._record_iterate_stream(exec_node_id, output)++ for reference_id, effects in self.execution_effects.items():+ execution_ref = next(+ (ref for ref in self.execution_refs.values() if ref.reference_id == reference_id),+ None,+ )+ if execution_ref is not None:+ self._validate_effects(execution_ref, list(effects), None)+ self._record_effect_streams(execution_ref, effects)++ for exec_node_id, node in self.execution_graph.nodes.items():+ if isinstance(node, ForInvocation) and node.index >= 0 and exec_node_id in self.results:+ continuation = self._for_continuation(exec_node_id)+ source_node_id = self.prepared_source_mapping.get(exec_node_id)+ if source_node_id is not None and self._is_loop_context_finalized(+ source_node_id, self._get_for_parent_iteration_path(exec_node_id)+ ):+ continuation.complete(self.results[exec_node_id].model_dump(mode="json"))++ self._register_generic_child_dependency()+def _rehydrate_ready_queues(self) -> None:if self.has_error():return@@ -5068,6 +5444,7 @@ class GraphExecutionState(BaseModel):self._reset_runtime_caches()self._rehydrate_prepared_exec_metadata()self._rehydrate_resolved_if_exec_branches()+ self._rehydrate_generic_runtime_state()self._rehydrate_ready_queues()def model_post_init(self, __context: Any) -> None:@@ -5262,6 +5639,7 @@ class GraphExecutionState(BaseModel):if len(set(child_item_ids)) != len(child_item_ids):raise ValueError("Workflow call child item ids must be unique.")self.waiting_workflow_call_execution.child_item_ids = list(child_item_ids)+ self._register_generic_child_dependency()def record_waiting_workflow_call_child_completion(self, child_item_id: int, output_values: dict[str, Any]diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.pyindex 95e52b55f7..ccb2719e6a 100644--- a/invokeai/app/services/shared/invocation_context.py+++ b/invokeai/app/services/shared/invocation_context.py@@ -984,7 +984,10 @@ class InvocationContext:self._services = services"""An internal API providing access to all application services. You probably shouldn't use this. It may change without warning."""source_node_id = getattr(data.invocation, "id", None) or data.source_invocation_id or "context"- self.execution_effects = execution_effects or ExecutionEffectsRecorder(source_node_id=source_node_id)+ self.execution_effects = execution_effects or ExecutionEffectsRecorder(+ source_node_id=source_node_id,+ frame_path=data.execution_frame,+ )"""Effects recorded during the current invocation run."""self.effects = self.execution_effects"""Alias for :attr:`execution_effects`."""diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.pyindex 09ffa43cdd..2d17c0e998 100644--- a/tests/app/services/shared/test_execution_effects.py+++ b/tests/app/services/shared/test_execution_effects.py@@ -27,9 +27,14 @@ from invokeai.app.services.shared.execution_effects import (SpawnExecutionEffect,UnsupportedExecutionEffectError,)+from invokeai.app.services.shared.execution_engine.child import ChildExecutionCapabilityfrom invokeai.app.services.shared.execution_state_migration import dump_execution_statefrom invokeai.app.services.shared.graph import Graph, GraphExecutionState-from invokeai.app.services.shared.invocation_context import InvocationContext+from invokeai.app.services.shared.invocation_context import (+ InvocationContext,+ InvocationContextData,+ build_invocation_context,+)@invocation_output("execution_effects_test_output")@@ -90,6 +95,22 @@ def _services(cache_size: int = 1) -> MagicMock:return services+def test_context_default_recorder_preserves_execution_frame() -> None:+ context = build_invocation_context(+ services=MagicMock(),+ data=InvocationContextData(+ queue_item=None, # type: ignore[arg-type]+ invocation=ExecutionEffectsTestInvocation(id="node"),+ source_invocation_id="source",+ execution_frame=(2, 1),+ ),+ is_canceled=lambda: False,+ )++ assert context.execution_effects.source_node_id == "node"+ assert context.execution_effects.frame_path == (2, 1)++def test_execution_token_and_ref_are_frame_aware() -> None:token = ExecutionToken(invocation_id="node", port="value", iteration_path=(2, 4))ref = ExecutionRef(token=token, scope="iteration")@@ -159,6 +180,53 @@ def test_execution_interface_spawn_is_guarded() -> None:)+def test_capability_enabled_execution_interface_records_child_lifecycle_effects() -> None:+ capability = ChildExecutionCapability(+ parent_execution_id="parent",+ parent_frame=(),+ authorization_context={"user_id": "user"},+ )+ recorder = ExecutionEffectsRecorder(+ source_node_id="parent",+ allow_lifecycle_effects=True,+ child_capability=capability,+ )+ execution = ExecutionInterface(recorder)++ handle = execution.spawn(graph={"nodes": {}}, inputs={})+ execution.await_dependency(ExecutionRef(execution_node_id="dependency"))+ execution.fail("failed")++ assert handle.child_execution_id+ assert handle.parent_execution_id == "parent"+ assert [effect.kind for effect in recorder.snapshot()] == ["spawn_execution", "await", "fail"]+ spawn = recorder.snapshot()[0]+ assert isinstance(spawn, SpawnExecutionEffect)+ assert spawn.child_execution_id == handle.child_execution_id+ assert spawn.authorization_context == {"user_id": "user"}+++def test_capability_enabled_execution_interface_rejects_wrong_parent_scope() -> None:+ capability = ChildExecutionCapability(parent_execution_id="other", parent_frame=())+ recorder = ExecutionEffectsRecorder(+ source_node_id="parent",+ allow_lifecycle_effects=True,+ child_capability=capability,+ )++ with pytest.raises(PermissionError, match="another execution"):+ ExecutionInterface(recorder).spawn(graph={"nodes": {}}, inputs={})+++def test_lifecycle_effects_require_a_child_capability() -> None:+ execution = ExecutionInterface(ExecutionEffectsRecorder(allow_lifecycle_effects=True))++ with pytest.raises(PermissionError, match="unavailable"):+ execution.await_dependency(ExecutionRef(execution_node_id="dependency"))+ with pytest.raises(PermissionError, match="unavailable"):+ execution.fail("failed")++@pytest.mark.parametrize("effect",[diff --git a/tests/app/services/shared/test_execution_engine_child.py b/tests/app/services/shared/test_execution_engine_child.pynew file mode 100644index 0000000000..626a84f61e--- /dev/null+++ b/tests/app/services/shared/test_execution_engine_child.py@@ -0,0 +1,220 @@+import json++import pytest+from pydantic import ValidationError++from invokeai.app.services.shared.execution_engine.child import (+ ChildCompletion,+ ChildDependencyCoordinator,+ ChildExecutionCapability,+ ChildExecutionRecord,+ ChildTerminalStatus,+)+++def _capability(**kwargs: object) -> ChildExecutionCapability:+ values: dict[str, object] = {+ "parent_execution_id": "parent",+ "parent_frame": ("outer", 2),+ "parent_reference_id": "parent-ref",+ "authorization_context": {"subject": "owner"},+ }+ values.update(kwargs)+ return ChildExecutionCapability(**values)+++def test_capability_binds_child_to_exact_parent_and_frame() -> None:+ capability = _capability()+ child = capability.create_child("child", child_frame=("outer", 2, 0), graph={"nodes": {}}, inputs={})++ assert child.parent_execution_id == "parent"+ assert child.parent_frame == ("outer", 2)+ assert child.child_frame == ("outer", 2, 0)+ assert child.depth == 1+ assert child.capability_id == capability.capability_id++ with pytest.raises(ValueError, match="parent frame"):+ capability.create_child("other", parent_frame=("wrong",))+ with pytest.raises(ValueError, match="parent"):+ capability.create_child("other", parent_execution_id="other")+ with pytest.raises(ValueError, match="child frame"):+ capability.create_child("other", child_frame=("wrong", 0))+++def test_capability_rejects_depth_count_and_capacity_limits() -> None:+ with pytest.raises(ValueError, match="depth"):+ _capability(depth=2, max_depth=2).create_child("child")+ with pytest.raises(ValueError, match="count"):+ _capability(max_children=1).create_dependency(["one", "two"])+ with pytest.raises(ValueError, match="capacity"):+ _capability(capacity=1).create_dependency(["one", "two"])+++def test_capability_limits_cumulative_child_creation() -> None:+ capability = _capability(max_children=2, capacity=1)++ child = capability.create_child("one")++ assert child.child_execution_id == "one"+ assert capability.remaining_capacity == 0+ with pytest.raises(ValueError, match="capacity"):+ capability.create_child("two")+ assert capability.remaining_capacity == 0+++def test_dependency_creation_does_not_leak_capacity_on_invalid_child() -> None:+ capability = _capability(capacity=2)++ with pytest.raises(ValueError, match="child frame"):+ capability.create_dependency(+ ["first", "second"],+ child_frames=[("outer", 2, 0), ("wrong", 1)],+ )++ assert capability.remaining_capacity == 2+++def test_continue_policy_reports_terminal_failure_after_all_children_finish() -> None:+ dependency = _capability(failure_policy="continue").create_dependency(["first", "second"])++ dependency.fail_child("first", "first failed")+ update = dependency.complete_child("second", {"value": 2})++ assert update.status == "failed"+ assert update.terminal+ assert dependency.error_message == "first failed"+++def test_dependency_rejects_duplicate_prebuilt_children() -> None:+ capability = _capability()+ child = capability.create_child("child")++ with pytest.raises(ValueError, match="unique"):+ capability.create_dependency(children=[child, child])+++def test_dependency_accepts_out_of_order_completion_but_aggregates_enqueue_order() -> None:+ capability = _capability()+ dependency = capability.create_dependency(["first", "middle", "last"], dependency_id="dependency")++ update = dependency.complete_child("last", {"value": "last"})+ assert update.terminal is False+ update = dependency.complete_child("first", {"value": "first"})+ assert update.terminal is False+ update = dependency.complete_child("middle", {"value": "middle"})++ assert update.status == "completed"+ assert update.aggregated_outputs == {"value": ["first", "middle", "last"]}+ assert dependency.completed_child_execution_ids == ["first", "middle", "last"]+++def test_dependency_is_idempotent_and_rejects_conflicting_or_foreign_completion() -> None:+ capability = _capability()+ dependency = capability.create_dependency(["child"], dependency_id="dependency")+ completed = dependency.complete_child("child", {"value": 1})+ receipt = dependency.completions["child"]++ duplicate = dependency.record_completion(receipt)+ assert duplicate.changed is False+ assert duplicate.status == "completed"++ with pytest.raises(ValueError, match="different terminal"):+ dependency.record_completion(+ ChildCompletion(+ child_execution_id="child",+ parent_execution_id="parent",+ parent_frame=("outer", 2),+ parent_reference_id="parent-ref",+ child_frame=("outer", 2, "child"),+ status="failed",+ error_message="late",+ )+ )+ assert completed.terminal is True++ with pytest.raises(ValueError, match="does not belong"):+ dependency.complete_child("other", {"value": 2})+++def test_failure_cancels_siblings_and_notifies_parent_once() -> None:+ capability = _capability(failure_policy="cancel_siblings")+ dependency = capability.create_dependency(["first", "second", "third"], dependency_id="dependency")++ update = dependency.fail_child("second", "child failed")++ assert update.status == "failed"+ assert update.parent_action == "failed"+ assert update.cancel_child_ids == ["first", "third"]+ assert update.terminal is True++ duplicate = dependency.fail_child("second", "child failed")+ assert duplicate.changed is False+ 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})++ raw = dependency.model_dump_json()+ restored = type(dependency).model_validate_json(raw)++ assert json.loads(raw)["children"][0]["capability_id"] == dependency.children[0].capability_id+ assert restored == dependency++ with pytest.raises(ValidationError, match="JSON-serializable"):+ _capability(authorization_context={"runtime": object()})+++def test_dependency_rejects_incomplete_completed_snapshot() -> None:+ dependency = _capability().create_dependency(["first", "second"], dependency_id="dependency")+ snapshot = dependency.model_dump(mode="python")+ snapshot.update(status="completed", terminal_transition_count=1)++ with pytest.raises(ValidationError, match="completed dependency"):+ type(dependency).model_validate(snapshot)+++def test_failed_child_requires_a_nonblank_error_message() -> None:+ dependency = _capability().create_dependency(["child"], dependency_id="dependency")++ with pytest.raises(ValidationError, match="error"):+ dependency.fail_child("child", "")++[email protected]("status", ["completed", "failed", "canceled"])+def test_terminal_statuses_are_explicit(status: ChildTerminalStatus) -> None:+ assert status in {"completed", "failed", "canceled"}diff --git a/tests/app/services/shared/test_execution_engine_primitives.py b/tests/app/services/shared/test_execution_engine_primitives.pynew file mode 100644index 0000000000..e47c6a98bc--- /dev/null+++ b/tests/app/services/shared/test_execution_engine_primitives.py@@ -0,0 +1,184 @@+from __future__ import annotations++import pytest+from pydantic import ValidationError++from invokeai.app.services.shared.execution_engine.primitives import (+ ActivationGate,+ ContinuationRecord,+ ExecutionFrame,+ StreamBuffer,+ StreamData,+ StreamEnd,+)+++def _frame(path: tuple[int | str, ...] = ()) -> ExecutionFrame:+ return ExecutionFrame(+ state_id="state",+ frame_id=f"state:{','.join(str(part) for part in path)}",+ iteration_path=path,+ workflow_call_depth=0,+ )+++def test_execution_frame_has_stable_full_identity() -> None:+ frame = _frame((2, "inner"))+ same_frame = ExecutionFrame.model_validate_json(frame.model_dump_json())++ assert frame == same_frame+ assert frame.identity == ("state", "state:2,inner", (2, "inner"), 0)+ assert frame.execution_id == "state"+ assert frame.path == (2, "inner")++ with pytest.raises(ValidationError):+ ExecutionFrame(state_id="", frame_id="frame")+++def test_activation_gate_resolves_once_per_owner_and_frame() -> None:+ gate = ActivationGate(+ gate_id="gate",+ owner_id="if-node",+ frame=_frame((0,)),+ branches=("true", "false"),+ )++ assert gate.resolve("true") is True+ assert gate.resolve("true") is False+ assert gate.selected_branch == "true"+ assert gate.is_active("true", owner_id="if-node", frame=_frame((0,)))+ assert not gate.is_active("false", owner_id="if-node", frame=_frame((0,)))++ with pytest.raises(ValueError, match="already resolved"):+ gate.resolve("false")+ with pytest.raises(ValueError, match="owner"):+ gate.is_active("true", owner_id="other", frame=_frame((0,)))+ with pytest.raises(ValueError, match="frame"):+ gate.is_active("true", owner_id="if-node", frame=_frame((1,)))+++def test_activation_gate_rejects_unknown_branch_without_mutation() -> None:+ gate = ActivationGate(+ gate_id="gate",+ owner_id="if-node",+ frame=_frame(),+ branches=("true", "false"),+ )++ with pytest.raises(ValueError, match="branch"):+ gate.resolve("other")+ assert gate.selected_branch is None+ assert gate.status == "pending"+++def test_stream_buffer_accepts_empty_stream() -> None:+ buffer = StreamBuffer[int](stream_id="stream", owner_id="iterate", frame=_frame())++ assert buffer.accept(StreamEnd(sequence=0)) is True+ assert buffer.accept(StreamEnd(sequence=0)) is False+ assert buffer.closed+ assert buffer.values == ()+ assert buffer.expected_sequence == 0+++def test_stream_buffer_preserves_order_and_none_values() -> None:+ buffer = StreamBuffer[int | None](stream_id="stream", owner_id="iterate", frame=_frame((1,)))++ assert buffer.append_data(3) is True+ assert buffer.append_data(None) is True+ assert buffer.close() is True++ assert buffer.values == (3, None)+ assert [event.sequence for event in buffer.events] == [0, 1, 2]+ assert isinstance(buffer.events[-1], StreamEnd)+++def test_stream_buffer_rejects_conflicting_duplicate_and_out_of_order_events() -> None:+ buffer = StreamBuffer[int](stream_id="stream", owner_id="iterate", frame=_frame())+ buffer.accept(StreamData(sequence=0, value=1))++ assert buffer.accept(StreamData(sequence=0, value=1)) is False+ with pytest.raises(ValueError, match="duplicate"):+ buffer.accept(StreamData(sequence=0, value=2))+ with pytest.raises(ValueError, match="order"):+ buffer.accept(StreamData(sequence=2, value=3))+ assert buffer.values == (1,)+ assert not buffer.closed+++def test_stream_buffer_rejects_data_after_close_without_mutation() -> None:+ buffer = StreamBuffer[int](stream_id="stream", owner_id="iterate", frame=_frame())+ buffer.close()++ with pytest.raises(ValueError, match="closed"):+ buffer.append_data(1)+ assert buffer.values == ()+ assert buffer.events == (StreamEnd(sequence=0),)+++def test_stream_buffer_validates_event_json_and_round_trips() -> None:+ buffer = StreamBuffer[dict[str, int]](stream_id="stream", owner_id="iterate", frame=_frame())+ buffer.append_data({"value": 1})+ buffer.close()++ restored = StreamBuffer[dict[str, int]].model_validate_json(buffer.model_dump_json())+ assert restored == buffer++ with pytest.raises(ValidationError):+ StreamData(sequence=0, value=object())+++def test_continuation_record_has_atomic_idempotent_status_transitions() -> None:+ continuation = ContinuationRecord[dict[str, int]](+ continuation_id="continuation",+ owner_id="owner",+ frame=_frame((2,)),+ kind="child",+ payload={"input": 1},+ )++ assert continuation.start() is True+ assert continuation.start() is False+ assert continuation.complete({"output": 2}) is True+ assert continuation.complete({"output": 2}) is False+ assert continuation.status == "completed"+ assert continuation.result == {"output": 2}++ with pytest.raises(ValueError, match="terminal"):+ continuation.fail("late failure")+ assert continuation.status == "completed"+ assert continuation.error is None+++def test_continuation_record_rejects_invalid_transition_without_mutation() -> None:+ continuation = ContinuationRecord(+ continuation_id="continuation",+ owner_id="owner",+ frame=_frame(),+ kind="child",+ )++ with pytest.raises(ValueError, match="transition"):+ continuation.complete("too early")+ assert continuation.status == "pending"+ assert continuation.result is None++ with pytest.raises(ValueError, match="owner"):+ continuation.assert_scope("other", _frame())+ assert continuation.status == "pending"+++def test_continuation_record_json_round_trip_preserves_none_result() -> None:+ continuation = ContinuationRecord(+ continuation_id="continuation",+ owner_id="owner",+ frame=_frame(),+ kind="loop",+ )+ continuation.start()+ continuation.complete(None)++ restored = ContinuationRecord.model_validate_json(continuation.model_dump_json())+ assert restored == continuation+ assert restored.status == "completed"+ assert restored.result is Nonediff --git a/tests/app/services/shared/test_execution_engine_runtime.py b/tests/app/services/shared/test_execution_engine_runtime.pynew file mode 100644index 0000000000..0014fecc36--- /dev/null+++ b/tests/app/services/shared/test_execution_engine_runtime.py@@ -0,0 +1,53 @@+from invokeai.app.services.shared.execution_engine.primitives import ExecutionFrame+from invokeai.app.services.shared.execution_engine.runtime import ExecutionEngineRuntime+++def _frame(path: tuple[int | str, ...] = ()) -> ExecutionFrame:+ return ExecutionFrame(+ state_id="state",+ frame_id=f"state:{path}",+ iteration_path=path,+ workflow_call_depth=0,+ )+++def test_runtime_keeps_gate_stream_and_continuation_scoped_by_full_frame() -> None:+ runtime = ExecutionEngineRuntime()+ root = _frame()+ child = _frame((0,))++ root_gate = runtime.register_gate("if", "if", root, ("true", "false"))+ child_gate = runtime.register_gate("if:child", "if", child, ("true", "false"))+ assert root_gate is not child_gate+ runtime.resolve_gate("if", "if", root, "true")+ assert runtime.get_gate("if").selected_branch == "true"+ assert runtime.get_gate("if:child").selected_branch is None++ stream = runtime.get_or_create_stream("iterate", "iterate", child)+ stream.append_data("value")+ stream.close()+ assert runtime.get_stream("iterate").values == ("value",)++ continuation = runtime.register_continuation("loop", "for", child, "loop")+ continuation.start()+ continuation.complete({"value": 1})+ assert runtime.get_continuation("loop").result == {"value": 1}+++def test_runtime_snapshot_round_trip_preserves_durable_records() -> None:+ runtime = ExecutionEngineRuntime()+ frame = _frame((2, "inner"))+ runtime.register_gate("gate", "if", frame, ("true", "false"))+ runtime.resolve_gate("gate", "if", frame, "false")+ stream = runtime.get_or_create_stream("stream", "iterate", frame)+ stream.append_data(None)+ stream.close()+ continuation = runtime.register_continuation("continuation", "for", frame, "loop")+ continuation.start()++ restored = ExecutionEngineRuntime.model_validate(runtime.model_dump(mode="json"))++ assert restored == runtime+ assert restored.get_gate("gate").is_active("false")+ assert restored.get_stream("stream").values == (None,)+ assert restored.get_continuation("continuation").status == "running"diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.pyindex 01722b6180..1bc7385a7b 100644--- a/tests/test_graph_execution_state.py+++ b/tests/test_graph_execution_state.py@@ -381,6 +381,48 @@ def test_graph_state_apply_accepts_close_stream_effect():assert token.token_kind == "stream_end"+def test_graph_state_apply_records_generic_effect_stream_and_rehydrates_it():+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ output = node.invoke(Mock(InvocationContext))+ ref = state.get_execution_ref(node.id, effect_count=2)++ state.apply(+ ref,+ output,+ effects=[+ {+ "kind": "emit",+ "token": {"node_id": node.id, "field": "value", "value": 3, "sequence": 0},+ "value": 3,+ },+ {+ "kind": "close_stream",+ "token": {+ "node_id": node.id,+ "field": "value",+ "token_kind": "stream_end",+ "sequence": 1,+ },+ },+ ],+ )++ streams = list(state._generic_runtime().streams.values())+ assert len(streams) == 1+ assert streams[0].closed+ assert streams[0].values == (3,)++ restored = TypeAdapter(GraphExecutionState).validate_json(state.model_dump_json(), strict=False)+ restored_streams = list(restored._generic_runtime().streams.values())+ assert len(restored_streams) == 1+ assert restored_streams[0].closed+ assert restored_streams[0].values == (3,)++@pytest.mark.parametrize("port", ["type", "output_meta", "loop_linkage"])@pytest.mark.parametrize("effect_kind, token_kind", [("emit", "data"), ("close_stream", "stream_end")])def test_graph_state_apply_rejects_reserved_effect_ports(port: str, effect_kind: str, token_kind: str):@@ -644,6 +686,70 @@ def test_graph_state_apply_rejects_emit_token_from_another_frame(token_frame: diassert not state.execution_effects+def test_graph_state_apply_rejects_emit_token_from_another_owner():+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ output = node.invoke(Mock(InvocationContext))+ ref = state.get_execution_ref(node.id, effect_count=1)++ with pytest.raises(ValueError, match="not owned"):+ state.apply(+ ref,+ output,+ effects=[+ {+ "kind": "emit",+ "execution_ref": {"execution_node_id": node.id},+ "token": {"node_id": "other", "field": "value", "value": 3},+ }+ ],+ )++ assert node.id not in state.executed+++def test_graph_state_apply_rejects_emit_without_a_token():+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ output = node.invoke(Mock(InvocationContext))+ ref = state.get_execution_ref(node.id, effect_count=1)++ with pytest.raises(ValueError, match="requires a data output token"):+ state.apply(+ ref,+ output,+ effects=[{"kind": "emit", "execution_ref": {"execution_node_id": node.id}}],+ )++ assert node.id not in state.executed+++def test_graph_state_rehydration_rejects_persisted_effect_token_from_another_owner():+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ output = node.invoke(Mock(InvocationContext))+ ref = state.get_execution_ref(node.id, effect_count=1)+ state.apply(+ ref,+ output,+ effects=[{"kind": "emit", "token": {"node_id": node.id, "field": "value", "value": 3}}],+ )+ snapshot = state.model_dump(mode="json")+ snapshot["execution_effects"][ref.reference_id][0]["token"]["node_id"] = "other"++ with pytest.raises(ValueError, match="not owned"):+ TypeAdapter(GraphExecutionState).validate_python(snapshot, strict=False)++def test_graph_state_apply_does_not_complete_when_effect_persistence_preparation_fails():class Uncopyable(BaseModel):value: int = 1@@ -1088,6 +1194,12 @@ def test_graph_for_rematerializes_indirect_body_for_each_iteration():assert state.results[after_exec_id].value == ["alpha", "beta"]assert state.is_complete()+ for exec_node_id, node in state.execution_graph.nodes.items():+ if isinstance(node, ForInvocation) and node.index >= 0:+ continuation = state._generic_runtime().get_continuation(f"{state.id}:for:{exec_node_id}")+ assert continuation.owner_id == exec_node_id+ assert continuation.status == "completed"+def test_graph_for_rematerializes_nested_iterate_body_through_collect():graph = Graph()@@ -2955,7 +3067,9 @@ def test_graph_record_waiting_workflow_call_child_completion_aggregates_named_vadef test_graph_record_waiting_workflow_call_child_completion_preserves_enqueue_order():- parent = GraphExecutionState(graph=Graph())+ parent_graph = Graph()+ parent_graph.add_node(AddInvocation(id="source-parent", a=1, b=2))+ parent = GraphExecutionState(graph=parent_graph)parent.execution_graph.add_node(AddInvocation(id="prepared-parent", a=1, b=2))parent.prepared_source_mapping["prepared-parent"] = "source-parent"@@ -2972,6 +3086,14 @@ def test_graph_record_waiting_workflow_call_child_completion_preserves_enqueue_oassert is_complete is Trueassert aggregated_values == {"sum": [3, 7]}+ restored = TypeAdapter(GraphExecutionState).validate_json(parent.model_dump_json(), strict=False)+ execution = restored.waiting_workflow_call_execution+ assert execution is not None+ generic_dependency = restored._generic_child_dependencies[execution.id]+ assert generic_dependency.status == "completed"+ assert generic_dependency.completions["101"].outputs == {"sum": 3}+ assert generic_dependency.completions["102"].outputs == {"sum": 7}+def test_graph_end_waiting_on_workflow_call_records_lifecycle_history():parent = GraphExecutionState(graph=Graph())@@ -4327,6 +4449,147 @@ def test_if_graph_optimized_behavior_records_skipped_branch_in_execution_historyassert g.executed_history.count("false_value") == 1+def test_if_graph_lowers_legacy_branch_choice_to_frame_scoped_activation_token():+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=True))+ graph.add_node(PromptTestInvocation(id="true_value", prompt="true branch"))+ graph.add_node(PromptTestInvocation(id="false_value", prompt="false branch"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_edge(create_edge("condition", "value", "if", "condition"))+ graph.add_edge(create_edge("true_value", "prompt", "if", "true_input"))+ graph.add_edge(create_edge("false_value", "prompt", "if", "false_input"))++ state = GraphExecutionState(graph=graph)+ execute_all_nodes(state)++ if_exec_id = next(iter(state.source_prepared_mapping["if"]))+ activation_tokens = [+ token+ for token in state.execution_tokens.values()+ if token.owner_node_id == if_exec_id and token.token_kind == "activation"+ ]+ assert len(activation_tokens) == 1+ assert activation_tokens[0].port == "true_input"+ assert activation_tokens[0].frame == state.get_execution_ref(if_exec_id).frame+ assert state._activation_gate(if_exec_id).is_active("true_input")+++def test_iterate_graph_records_a_closed_frame_scoped_stream_for_collect():+ graph = Graph()+ graph.add_node(BooleanCollectionInvocation(id="values", collection=[True, False]))+ graph.add_node(IterateInvocation(id="iterate"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("values", "collection", "iterate", "collection"))+ graph.add_edge(create_edge("iterate", "item", "collect", "item"))++ state = GraphExecutionState(graph=graph)+ execute_all_nodes(state)++ streams = [stream for stream in state._generic_runtime().streams.values() if stream.owner_id == "iterate"]+ assert len(streams) == 1+ assert streams[0].closed+ assert streams[0].values == (True, False)+++def test_generic_control_records_rehydrate_from_runtime_snapshot():+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=True))+ graph.add_node(PromptTestInvocation(id="true_value", prompt="true branch"))+ graph.add_node(PromptTestInvocation(id="false_value", prompt="false branch"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_edge(create_edge("condition", "value", "if", "condition"))+ graph.add_edge(create_edge("true_value", "prompt", "if", "true_input"))+ graph.add_edge(create_edge("false_value", "prompt", "if", "false_input"))++ state = GraphExecutionState(graph=graph)+ execute_all_nodes(state)+ restored = TypeAdapter(GraphExecutionState).validate_json(state.model_dump_json(), strict=False)++ if_exec_id = next(iter(restored.source_prepared_mapping["if"]))+ assert restored._activation_gate(if_exec_id).selected_branch == "true_input"+ assert any(+ token.owner_node_id == if_exec_id and token.token_kind == "activation"+ for token in restored.execution_tokens.values()+ )+++def test_if_snapshot_rejects_conflicting_activation_tokens():+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=True))+ graph.add_node(PromptTestInvocation(id="true_value", prompt="true branch"))+ graph.add_node(PromptTestInvocation(id="false_value", prompt="false branch"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_edge(create_edge("condition", "value", "if", "condition"))+ graph.add_edge(create_edge("true_value", "prompt", "if", "true_input"))+ graph.add_edge(create_edge("false_value", "prompt", "if", "false_input"))++ state = GraphExecutionState(graph=graph)+ execute_all_nodes(state)+ snapshot = state.model_dump(mode="json")+ activation_id, activation = next(+ (token_id, token)+ for token_id, token in snapshot["execution_tokens"].items()+ if token["token_kind"] == "activation"+ )+ conflicting_id = f"{activation_id}:conflict"+ snapshot["execution_tokens"][conflicting_id] = {+ **activation,+ "token_id": conflicting_id,+ "port": "false_input",+ "value": "false_input",+ }++ with pytest.raises(ValueError, match="conflicting activation tokens"):+ TypeAdapter(GraphExecutionState).validate_python(snapshot, strict=False)+++def test_if_snapshot_rejects_activation_token_with_contradictory_value():+ graph = Graph()+ graph.add_node(BooleanInvocation(id="condition", value=True))+ graph.add_node(PromptTestInvocation(id="true_value", prompt="true branch"))+ graph.add_node(PromptTestInvocation(id="false_value", prompt="false branch"))+ graph.add_node(IfInvocation(id="if"))+ graph.add_edge(create_edge("condition", "value", "if", "condition"))+ graph.add_edge(create_edge("true_value", "prompt", "if", "true_input"))+ graph.add_edge(create_edge("false_value", "prompt", "if", "false_input"))++ state = GraphExecutionState(graph=graph)+ execute_all_nodes(state)+ snapshot = state.model_dump(mode="json")+ token_id, token = next(+ (token_id, token)+ for token_id, token in snapshot["execution_tokens"].items()+ if token["token_kind"] == "activation"+ )+ snapshot["execution_tokens"][token_id] = {**token, "value": "false_input"}++ with pytest.raises(ValueError, match="stale value"):+ TypeAdapter(GraphExecutionState).validate_python(snapshot, strict=False)+++def test_empty_iterate_graph_records_a_closed_empty_stream():+ graph = Graph()+ graph.add_node(BooleanCollectionInvocation(id="values", collection=[]))+ graph.add_node(IterateInvocation(id="iterate", collection=[]))+ graph.add_edge(create_edge("values", "collection", "iterate", "collection"))++ state = GraphExecutionState(graph=graph)+ execute_all_nodes(state)++ streams = [stream for stream in state._generic_runtime().streams.values() if stream.owner_id == "iterate"]+ assert len(streams) == 1+ assert streams[0].closed+ assert streams[0].values == ()++ restored = TypeAdapter(GraphExecutionState).validate_json(state.model_dump_json(), strict=False)+ restored_streams = [+ stream for stream in restored._generic_runtime().streams.values() if stream.owner_id == "iterate"+ ]+ assert len(restored_streams) == 1+ assert restored_streams[0].closed+ assert restored_streams[0].values == ()++def test_if_graph_optimized_behavior_skips_unselected_branch_but_keeps_shared_ancestors():graph = Graph()graph.add_node(BooleanInvocation(id="condition", value=True))