Skip to content

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.

fix(execution): preserve loop state across rehydration

JPPhoto514fe47a6361
diff --git a/docs/src/content/docs/contributing/call-saved-workflow.md b/docs/src/content/docs/contributing/call-saved-workflow.md
index 5624c7005b..fde280f777 100644
--- a/docs/src/content/docs/contributing/call-saved-workflow.md
+++ b/docs/src/content/docs/contributing/call-saved-workflow.md
@@ -22,9 +22,11 @@ queue boundary for durable rows and queue transitions, while invocation and grap
effect/dependency seam to declare, persist, and resume the call.
The callable node, saved-workflow, and queue interaction contract is stable. Internal execution references, tokens,
-effects, frames, and scheduler records are persistence-only implementation metadata. `dump_execution_state()` retains
-`execution_refs`, `execution_tokens`, `execution_effects`, and `execution_child_dependencies`, including attached child
-states. Ordinary model serialization and public schemas exclude these four internal ledgers. Existing fields,
+effects, frames, and scheduler records are persistence-only implementation metadata. Version-2
+`dump_execution_state()` rebuilds execution references and ordinary output tokens, retains frame-scoped activation
+tokens and effects needed for active recovery, and omits terminal saved-workflow lifecycle effects and completed child
+dependencies. Attached child state is retained while a call is active and omitted after the call is terminal.
+Ordinary model serialization and public schemas exclude these four internal ledgers. Existing fields,
requiredness, statuses, events, and client behavior remain compatible. Frontend application behavior is outside this
backend architecture. No code under `invokeai/frontend/...`, including generated `openapi.json` or `schema.ts`, is part
of this execution behavior; the existing frontend/backend external interface is stable.
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 8b00e9061b..b68cee4a09 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -31,8 +31,10 @@ helpers, while successor readiness is selected from frame-scoped dependencies an
Ownership is topology-dependent: admitted fresh `If` branches require matching activation tokens; bounded planners own
admitted loop expansion and continuation. Compatibility adapters own the remaining shapes. Execution ledgers are
-internal persistence data, excluded from ordinary model serialization and public schemas. `dump_execution_state()`
-retains them, including attached child states. They add no author-time ports or frontend/backend external fields.
+internal persistence data, excluded from ordinary model serialization and public schemas. Version-2
+`dump_execution_state()` rebuilds references and ordinary output tokens, retains activation tokens and effects needed
+for resume, and omits terminal lifecycle records and completed child dependencies. They add no author-time ports or
+frontend/backend external fields.
## Core contract
diff --git a/invokeai/app/invocations/call_saved_workflow.py b/invokeai/app/invocations/call_saved_workflow.py
index a68488c6e9..8a62962a07 100644
--- a/invokeai/app/invocations/call_saved_workflow.py
+++ b/invokeai/app/invocations/call_saved_workflow.py
@@ -1,3 +1,4 @@
+import traceback
from typing import Any
from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation
@@ -101,7 +102,11 @@ class CallSavedWorkflowInvocation(BaseInvocation):
)
except Exception as e:
if lifecycle_enabled:
- execution.fail(str(e))
+ execution.fail(
+ str(e),
+ error_type=type(e).__name__,
+ error_traceback=traceback.format_exc(),
+ )
return WorkflowReturnOutput(values={})
raise
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index 17e4f83b51..06b113d945 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -342,13 +342,15 @@ class DefaultSessionRunner(SessionRunnerBase):
None,
)
if failure_effect is not None:
- error_message = str(getattr(failure_effect, "message", "saved workflow call failed"))
+ error_message = str(getattr(failure_effect, "message", ""))
+ error_type = getattr(failure_effect, "error_type", None) or "ValueError"
+ error_traceback = getattr(failure_effect, "error_traceback", None) or error_message
self._on_node_error(
invocation=invocation,
queue_item=queue_item,
- error_type="ValueError",
+ error_type=error_type,
error_message=error_message,
- error_traceback=error_message,
+ error_traceback=error_traceback,
)
return
diff --git a/invokeai/app/services/session_processor/workflow_call_runtime.py b/invokeai/app/services/session_processor/workflow_call_runtime.py
index 9b51216134..342c66593c 100644
--- a/invokeai/app/services/session_processor/workflow_call_runtime.py
+++ b/invokeai/app/services/session_processor/workflow_call_runtime.py
@@ -170,7 +170,7 @@ class WorkflowCallQueueLifecycle:
"Workflow call lifecycle effects must contain either one fail or one spawn+await pair."
)
message = self._effect_value(fail_effects[0], "message")
- if not isinstance(message, str) or not message.strip():
+ if not isinstance(message, str):
raise ValueError("Workflow call fail effect requires an error message.")
raise ValueError(message)
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 66c810ef6f..aa67fffb60 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -42,8 +42,11 @@ invocation, frontend, generated-schema, image, or external-interface contract. T
for every currently supported fresh shape listed above. The controller remains required for unsupported fresh shapes
and legacy snapshots. The execution ledgers (`execution_refs`, `execution_tokens`, `execution_effects`, and
`execution_child_dependencies`) are internal persistence data. They are not part of public API schemas or client
-responses; `dump_execution_state()` is the explicit internal persistence path that retains them, including nested child
-states. Direct `Iterate`/`Collect` graphs that do not contain `If`, `For`, `ForReturn`, or saved-workflow control flow
+responses. Version-2 `dump_execution_state()` writes a compact projection: execution references and ordinary output
+tokens are rebuilt from the prepared graph, mappings, and results; frame-scoped activation tokens remain durable;
+effects remain durable when needed for stream, continuation, or active workflow-call recovery; completed workflow-call
+lifecycle effects and completed child-dependency records are omitted. Attached child state is retained only while its
+parent call is active. Direct `Iterate`/`Collect` graphs that do not contain `If`, `For`, `ForReturn`, or saved-workflow control flow
also use the generic adapter. Its adapter-level readiness predicate waits for canonical Iterate streams to close, and
generic completion mirrors each Iterate result into that ledger before releasing `Collect`. The exact fresh four-node
shape `literal collection source -> Iterate -> one ordinary body -> Collect`, plus any number of ordinary downstream
@@ -302,9 +305,10 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre
- source node id
- iteration path
- runtime state such as pending, ready, executed, or skipped
-- `execution_refs: dict[str, ExecutionReference]` - stable references for prepared execution nodes, including their
- source node and execution frame.
-- `execution_tokens: dict[str, ExecutionToken]` - output tokens produced by applied execution results.
+- `execution_refs: dict[str, ExecutionReference]` - in-memory stable references for prepared execution nodes, including
+ their source node and execution frame; version-2 snapshots rebuild these references instead of storing them.
+- `execution_tokens: dict[str, ExecutionToken]` - in-memory output tokens produced by applied execution results;
+ version-2 snapshots retain only frame-scoped activation tokens.
- `execution_effects: dict[str, list[Any]]` - JSON-safe effects accepted for each execution reference.
- **Ready queues grouped by class** (private projection): `_ready_queues: dict[class_name, deque[str]]` and
`_active_class: Optional[str]`. Ordinary static DAGs and legacy-shaped `If` graphs derive readiness from the generic
@@ -573,11 +577,13 @@ remain excluded from ready-queue projection during rehydration, preserving ready
the pending `If` is admitted. Before token validation, missing legacy iteration-path metadata is rebuilt from the
prepared execution graph. Persisted activation identity is then validated fail-closed against prepared owners, derived
references, declared activation fields, canonical ids, and known frame fields; extra frame metadata is retained.
-`dump_execution_state()` retains execution references, tokens, effects, and child dependencies, including those in
-attached child states. Ordinary model serialization and public schemas omit these four internal ledgers; private helper
-objects are not serialized. Queue snapshots carry an additive execution-state version marker and use a version-aware
-loader; legacy unmarked snapshots are treated as version 0, while unreadable snapshots are quarantined by queue
-service.
+Version-2 `dump_execution_state()` omits derived execution references and ordinary output tokens, keeps activation
+tokens, retains stream/continuation effects needed to resume, and drops terminal saved-workflow lifecycle effects and
+completed child-dependency records. Active workflow-call child state remains attached for recovery; completed calls use
+their workflow-call history instead. Ordinary model serialization and public schemas omit these four internal ledgers;
+private helper objects are not serialized. Queue snapshots carry an additive execution-state version marker and use a
+version-aware loader; legacy unmarked snapshots are treated as version 0, while unreadable snapshots are quarantined by
+queue service.
### 4.4 Compatibility preparation (`_prepare()`)
diff --git a/invokeai/app/services/shared/execution_effects.py b/invokeai/app/services/shared/execution_effects.py
index 583e1c06de..bb3f83bd40 100644
--- a/invokeai/app/services/shared/execution_effects.py
+++ b/invokeai/app/services/shared/execution_effects.py
@@ -334,7 +334,9 @@ class AwaitEffect(ExecutionEffect):
class FailEffect(ExecutionEffect):
kind: Literal["fail"] = "fail"
- message: str = Field(min_length=1)
+ message: str = Field(default="")
+ error_type: str | None = Field(default=None, min_length=1)
+ error_traceback: str | None = None
class ContinuationEffect(ExecutionEffect):
@@ -456,9 +458,22 @@ class ExecutionInterface:
self._require_lifecycle_capability("await")
self._recorder.record(AwaitEffect(execution_ref=self._recorder.execution_ref, dependency=dependency))
- def fail(self, message: str) -> None:
+ def fail(
+ self,
+ message: str,
+ *,
+ error_type: str | None = None,
+ error_traceback: str | None = None,
+ ) -> None:
self._require_lifecycle_capability("fail")
- self._recorder.record(FailEffect(execution_ref=self._recorder.execution_ref, message=message))
+ self._recorder.record(
+ FailEffect(
+ execution_ref=self._recorder.execution_ref,
+ message=message,
+ error_type=error_type,
+ error_traceback=error_traceback,
+ )
+ )
def start_continuation(self, continuation_kind: str, *, payload: Any | None = None) -> None:
self._recorder.record(
diff --git a/invokeai/app/services/shared/execution_state_migration.py b/invokeai/app/services/shared/execution_state_migration.py
index 15f74dd7ed..cd54eeaa20 100644
--- a/invokeai/app/services/shared/execution_state_migration.py
+++ b/invokeai/app/services/shared/execution_state_migration.py
@@ -3,9 +3,10 @@
from collections.abc import Callable, Mapping
from typing import Any, Final
+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
from invokeai.app.services.shared.graph import GraphExecutionState
-CURRENT_EXECUTION_STATE_VERSION: Final[int] = 1
+CURRENT_EXECUTION_STATE_VERSION: Final[int] = 2
LEGACY_EXECUTION_STATE_VERSION: Final[int] = 0
@@ -23,13 +24,74 @@ def _retain_nullable_execution_token_values(snapshot: dict[str, Any]) -> None:
_retain_nullable_execution_token_values(child_snapshot)
-def _append_runtime_fields(snapshot: dict[str, Any], state: GraphExecutionState) -> None:
- """Add private runtime ledgers to an internal snapshot, including child states."""
- snapshot["execution_refs"] = {
- reference_id: reference.model_dump(mode="json") for reference_id, reference in state.execution_refs.items()
+def _object_value(value: Any, name: str, default: Any = None) -> Any:
+ if isinstance(value, dict):
+ return value.get(name, default)
+ return getattr(value, name, default)
+
+
+def _completed_workflow_call_ids(state: GraphExecutionState) -> set[str]:
+ return {
+ execution.prepared_call_node_id
+ for execution in state.workflow_call_history
+ if execution.status in {"completed", "failed"}
}
+
+
+def _compact_effects(snapshot: dict[str, Any], state: GraphExecutionState) -> None:
+ """Drop terminal saved-workflow lifecycle effects whose history is authoritative.
+
+ Active lifecycle effects and all stream/continuation effects remain authoritative for recovery and validation.
+ A completed saved-workflow call has already copied its child result into the parent history, so retaining the
+ spawn effect would retain the child graph and inputs for no recovery purpose. Unknown effect shapes stay durable
+ for forward compatibility.
+ """
+ references_by_id = {reference.reference_id: reference for reference in state.execution_refs.values()}
+ completed_workflow_calls = _completed_workflow_call_ids(state)
+ compacted: dict[str, list[Any]] = {}
+ for reference_id, effects in snapshot["execution_effects"].items():
+ reference = references_by_id.get(reference_id)
+ node = state.execution_graph.nodes.get(reference.exec_node_id) if reference is not None else None
+ drop_workflow_lifecycle = (
+ isinstance(node, CallSavedWorkflowInvocation)
+ and reference is not None
+ and reference.exec_node_id in state.executed
+ and reference.exec_node_id in completed_workflow_calls
+ )
+ retained: list[Any] = []
+ for effect in effects:
+ effect_kind = (
+ _object_value(effect, "kind") or _object_value(effect, "effect_type") or _object_value(effect, "type")
+ )
+ if drop_workflow_lifecycle and effect_kind in {"spawn_execution", "await", "fail"}:
+ continue
+ retained.append(effect)
+ if retained or not drop_workflow_lifecycle:
+ compacted[reference_id] = retained
+ snapshot["execution_effects"] = compacted
+
+
+def _compact_child_dependencies(snapshot: dict[str, Any], state: GraphExecutionState) -> None:
+ """Drop completed dependency records after the parent has left its waiting boundary."""
+ if state.waiting_workflow_call_execution is not None:
+ return
+ snapshot["execution_child_dependencies"] = {
+ dependency_id: dependency
+ for dependency_id, dependency in snapshot["execution_child_dependencies"].items()
+ if _object_value(dependency, "status") != "completed"
+ }
+
+
+def _append_runtime_fields(snapshot: dict[str, Any], state: GraphExecutionState) -> None:
+ """Add compact private runtime ledgers to an internal snapshot, including child states."""
+ # References are derived from the prepared execution graph and mappings during rehydration. Do not serialize
+ # them before dropping them: large loop snapshots otherwise pay the full copy/serialization cost for data that
+ # never crosses the persistence boundary.
+ snapshot["execution_refs"] = {}
snapshot["execution_tokens"] = {
- token_id: token.model_dump(mode="json") for token_id, token in state.execution_tokens.items()
+ token_id: token.model_dump(mode="json")
+ for token_id, token in state.execution_tokens.items()
+ if token.token_kind == "activation"
}
snapshot["execution_effects"] = {
reference_id: [
@@ -46,6 +108,9 @@ def _append_runtime_fields(snapshot: dict[str, Any], state: GraphExecutionState)
effect.model_dump(mode="json") if hasattr(effect, "model_dump") else effect for effect in effects
]
+ _compact_effects(snapshot, state)
+ _compact_child_dependencies(snapshot, state)
+
child_snapshot = snapshot.get("waiting_workflow_call_child_session")
child_state = state.waiting_workflow_call_child_session
if isinstance(child_snapshot, dict) and child_state is not None:
@@ -81,16 +146,23 @@ def _migrate_legacy_snapshot(payload: Mapping[str, Any]) -> dict[str, Any]:
def _migrate_v1_snapshot(payload: Mapping[str, Any]) -> dict[str, Any]:
- """Validate the v1 payload boundary before a future migration is added."""
+ """Carry the full v1 payload forward; v2 changes only the dump projection."""
+
+ return dict(payload)
+
+
+def _migrate_v2_snapshot(payload: Mapping[str, Any]) -> dict[str, Any]:
+ """Validate the compact v2 payload boundary before a future migration is added."""
return dict(payload)
-# Each key is the source version. A future version bump must add its v1 -> v2
+# Each key is the source version. A future version bump must add its v2 -> v3
# converter here before changing CURRENT_EXECUTION_STATE_VERSION.
_SNAPSHOT_MIGRATIONS: dict[int, Callable[[Mapping[str, Any]], dict[str, Any]]] = {
LEGACY_EXECUTION_STATE_VERSION: _migrate_legacy_snapshot,
- CURRENT_EXECUTION_STATE_VERSION: _migrate_v1_snapshot,
+ 1: _migrate_v1_snapshot,
+ CURRENT_EXECUTION_STATE_VERSION: _migrate_v2_snapshot,
}
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 199f66303a..018f09da5d 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -321,6 +321,11 @@ class GraphExecutionState(BaseModel):
PrivateAttr(default_factory=dict)
)
_if_activation_dependencies_by_exec: dict[str, tuple[ActivationDependency, ...]] = PrivateAttr(default_factory=dict)
+ _prepared_if_exec_ids_by_source_and_frame: dict[tuple[str, tuple[int, ...]], tuple[str, ...]] = PrivateAttr(
+ default_factory=dict
+ )
+ _prepared_if_exec_frames_by_source: dict[str, tuple[tuple[int, ...], ...]] = PrivateAttr(default_factory=dict)
+ _prepared_if_exec_indexed_sources: set[str] = PrivateAttr(default_factory=set)
_prepared_exec_metadata: dict[str, _PreparedExecNodeMetadata] = PrivateAttr(default_factory=dict)
_prepared_exec_registry: Optional[_PreparedExecRegistry] = PrivateAttr(default=None)
_if_activation_controller_instance: Optional[_IfActivationController] = PrivateAttr(default=None)
@@ -447,6 +452,9 @@ class GraphExecutionState(BaseModel):
self._if_branch_sources_cache = {}
self._if_activation_dependencies_by_source = {}
self._if_activation_dependencies_by_exec = {}
+ self._prepared_if_exec_ids_by_source_and_frame = {}
+ self._prepared_if_exec_frames_by_source = {}
+ self._prepared_if_exec_indexed_sources = set()
self._execution_runtime = None
self._source_graph_flat = None
self._execution_graph_flat = None
@@ -458,6 +466,16 @@ class GraphExecutionState(BaseModel):
self._prepared_for_index = None
self._final_prepared_for_index = None
self._prepared_for_index_by_exec = {}
+ self._prepared_if_exec_ids_by_source_and_frame = {}
+ self._prepared_if_exec_frames_by_source = {}
+ self._prepared_if_exec_indexed_sources = set()
+ self._pending_if_exec_nodes = {
+ exec_node_id
+ for exec_node_id, node in self.execution_graph.nodes.items()
+ if exec_node_id not in self.executed
+ and isinstance(node, IfInvocation)
+ and self._is_pending_if(exec_node_id)
+ }
def _type_key(self, node_obj: BaseInvocation) -> str:
return node_obj.__class__.__name__
@@ -474,6 +492,30 @@ class GraphExecutionState(BaseModel):
)
return self._prepared_exec_registry
+ def _prepared_if_exec_ids(self, source_node_id: str, iteration_path: tuple[int, ...]) -> tuple[str, ...]:
+ """Return prepared If executions for one source/frame without rescanning them per dependency check."""
+ if source_node_id not in self._prepared_if_exec_indexed_sources:
+ frame_paths: list[tuple[int, ...]] = []
+ for exec_node_id in self.source_prepared_mapping.get(source_node_id, ()):
+ if not isinstance(self.execution_graph.nodes.get(exec_node_id), IfInvocation):
+ continue
+ prepared_path = self._get_iteration_path(exec_node_id)
+ if prepared_path is None:
+ continue
+ key = (source_node_id, prepared_path)
+ existing = self._prepared_if_exec_ids_by_source_and_frame.get(key, ())
+ self._prepared_if_exec_ids_by_source_and_frame[key] = (*existing, exec_node_id)
+ if not existing:
+ frame_paths.append(prepared_path)
+ self._prepared_if_exec_frames_by_source[source_node_id] = tuple(frame_paths)
+ self._prepared_if_exec_indexed_sources.add(source_node_id)
+ return self._prepared_if_exec_ids_by_source_and_frame.get((source_node_id, iteration_path), ())
+
+ def _prepared_if_exec_frames(self, source_node_id: str) -> tuple[tuple[int, ...], ...]:
+ """Return indexed If frames for one source."""
+ self._prepared_if_exec_ids(source_node_id, ())
+ return self._prepared_if_exec_frames_by_source.get(source_node_id, ())
+
def _if_activation_controller(self) -> _IfActivationController:
if self._if_activation_controller_instance is None:
self._if_activation_controller_instance = _IfActivationController(self)
@@ -1918,6 +1960,11 @@ class GraphExecutionState(BaseModel):
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_if_exec_indexed_sources.discard(source_node_id)
+ for key in tuple(self._prepared_if_exec_ids_by_source_and_frame):
+ if key[0] == source_node_id:
+ self._prepared_if_exec_ids_by_source_and_frame.pop(key, None)
+ self._prepared_if_exec_frames_by_source.pop(source_node_id, None)
is_new = exec_node_id not in self.source_prepared_mapping.get(source_node_id, ())
self._prepared_registry().register(exec_node_id, source_node_id)
if is_new and self._unexecuted_prepared_counts is not None and exec_node_id not in self.executed:
@@ -2295,7 +2342,7 @@ class GraphExecutionState(BaseModel):
awaited_child_ids.append(child_execution_id)
elif effect_kind == "fail":
message = self._value_from_object(effect, "message")
- if not isinstance(message, str) or not message.strip():
+ if not isinstance(message, str):
raise ValueError("Fail effect requires an error message")
token = self._value_from_object(effect, "token")
@@ -2715,6 +2762,11 @@ class GraphExecutionState(BaseModel):
def _invalidate_loop_caches_for_exec_node(self, exec_node_id: str) -> None:
source_node_id = self.prepared_source_mapping.get(exec_node_id)
if source_node_id is not None:
+ self._prepared_if_exec_indexed_sources.discard(source_node_id)
+ for key in tuple(self._prepared_if_exec_ids_by_source_and_frame):
+ if key[0] == source_node_id:
+ self._prepared_if_exec_ids_by_source_and_frame.pop(key, None)
+ self._prepared_if_exec_frames_by_source.pop(source_node_id, None)
self._invalidate_loop_caches_for_source(source_node_id)
prepared_node = self.execution_graph.nodes.get(exec_node_id)
if isinstance(prepared_node, ForInvocation):
@@ -3046,6 +3098,8 @@ class GraphExecutionState(BaseModel):
self._if_activation_controller_instance = None
self._if_activation_dependencies_by_source = {}
self._if_activation_dependencies_by_exec = {}
+ self._prepared_if_exec_ids_by_source_and_frame = {}
+ self._prepared_if_exec_indexed_sources = set()
self._source_graph_flat = None
self._execution_graph_flat = None
self._completed_source_ids_cache = None
@@ -3118,15 +3172,15 @@ class GraphExecutionState(BaseModel):
def _rehydrate_resolved_if_exec_branches(self) -> None:
self._validate_persisted_activation_tokens()
+ activation_tokens_by_owner: dict[str, list[ExecutionToken]] = {}
+ for token in self.execution_tokens.values():
+ if token.token_kind == "activation":
+ activation_tokens_by_owner.setdefault(token.owner_node_id, []).append(token)
for exec_node_id, node in self.execution_graph.nodes.items():
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"
- ]
+ activation_tokens = activation_tokens_by_owner.get(exec_node_id, [])
if activation_tokens:
expected_ref = self._expected_execution_ref(exec_node_id)
selected_fields: set[str] = set()
diff --git a/invokeai/app/services/shared/graph_if_runtime.py b/invokeai/app/services/shared/graph_if_runtime.py
index a90018611d..bc2d71efb8 100644
--- a/invokeai/app/services/shared/graph_if_runtime.py
+++ b/invokeai/app/services/shared/graph_if_runtime.py
@@ -49,9 +49,9 @@ def _is_source_inactive(
return any(state._is_activation_dependency_rejected(dependency) for dependency in dependencies)
frames = {
- state._get_iteration_path(exec_node_id)
+ iteration_path
for dependency in dependencies
- for exec_node_id in state._prepared_registry().get_prepared_ids(dependency.owner_id)
+ for iteration_path in state._prepared_if_exec_frames(dependency.owner_id)
}
if not frames:
return all(_is_empty_if_condition(state, dependency) for dependency in dependencies)
@@ -113,11 +113,7 @@ def _record_compatibility_activation_token(
def _is_activation_dependency_satisfied(state: "GraphExecutionState", dependency: ActivationDependency) -> bool:
"""Check one opaque plan requirement against durable gate and token state."""
- matching_gate_ids = [
- prepared_if_id
- for prepared_if_id in state._prepared_registry().get_prepared_ids(dependency.owner_id)
- if state._get_iteration_path(prepared_if_id) == dependency.frame
- ]
+ matching_gate_ids = state._prepared_if_exec_ids(dependency.owner_id, dependency.frame)
if not matching_gate_ids:
return False
@@ -134,7 +130,8 @@ def _is_activation_dependency_satisfied(state: "GraphExecutionState", dependency
return False
if not gate.is_active(dependency.branch, owner_id=gate_id, frame=gate.frame):
return False
- if not any(
+ token = state.execution_tokens.get(f"{expected_ref.reference_id}:activation:{dependency.branch}")
+ if token is None or not (
token.token_id == f"{expected_ref.reference_id}:activation:{dependency.branch}"
and token.reference_id == expected_ref.reference_id
and token.owner_node_id == gate_id
@@ -145,7 +142,6 @@ def _is_activation_dependency_satisfied(state: "GraphExecutionState", dependency
and token.frame.frame_id == expected_ref.frame.frame_id
and token.frame.iteration_path == expected_ref.frame.iteration_path
and token.frame.workflow_call_depth == expected_ref.frame.workflow_call_depth
- for token in state.execution_tokens.values()
):
return False
return True
@@ -154,11 +150,7 @@ def _is_activation_dependency_satisfied(state: "GraphExecutionState", dependency
def _is_activation_dependency_rejected(state: "GraphExecutionState", dependency: ActivationDependency) -> bool:
"""Return whether a resolved gate explicitly selected another branch."""
- matching_gate_ids = [
- prepared_if_id
- for prepared_if_id in state._prepared_registry().get_prepared_ids(dependency.owner_id)
- if state._get_iteration_path(prepared_if_id) == dependency.frame
- ]
+ matching_gate_ids = state._prepared_if_exec_ids(dependency.owner_id, dependency.frame)
for gate_id in matching_gate_ids:
gate = state._activation_gate(gate_id)
expected_frame = state._expected_execution_ref(gate_id).frame
diff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.py
index 99bf64626b..a9504e2179 100644
--- a/invokeai/app/services/shared/graph_materializer.py
+++ b/invokeai/app/services/shared/graph_materializer.py
@@ -1406,6 +1406,18 @@ class _ExecutionNodeBuilder:
else:
mappings = self._get_parent_iteration_mappings(node_id, graph)
mappings = list(mappings)
+ if isinstance(self._state.graph.get_node(node_id), IfInvocation) and self.get_node_iterators(
+ node_id, self.iterator_graph(graph)
+ ):
+ if not any(mappings):
+ iterator_nodes = self.get_node_iterators(node_id, self.iterator_graph(graph))
+ if all(
+ iterator_node_id in self._state.executed
+ and not self._state.source_prepared_mapping.get(iterator_node_id)
+ for iterator_node_id in iterator_nodes
+ ):
+ return True
+ return False
if not mappings:
return self._state._is_source_activation_admitted(node_id)
return any(
@@ -1419,9 +1431,54 @@ class _ExecutionNodeBuilder:
self, node_id: str, graph: "nx.DiGraph"
) -> Iterable[list[tuple[str, str]]]:
condition_edges = self._state.graph._get_input_edges(node_id, "condition")
- if not condition_edges:
+ iterator_graph = self.iterator_graph(graph)
+ iterator_nodes = self.get_node_iterators(node_id, iterator_graph)
+ if condition_edges and not iterator_nodes:
+ return self._get_parent_iteration_mappings(node_id, graph, input_edges=condition_edges)
+ if not iterator_nodes:
return iter([[]])
- return self._get_parent_iteration_mappings(node_id, graph, input_edges=condition_edges)
+
+ if condition_edges and any(
+ edge.source.node_id == iterator_nodes[0]
+ or nx.has_path(iterator_graph, iterator_nodes[0], edge.source.node_id)
+ for edge in condition_edges
+ ):
+ return self._get_parent_iteration_mappings(node_id, graph, input_edges=condition_edges)
+
+ # This bounded path derives one frame axis. Leave mixed/nested axes on the existing path because
+ # _get_known_iteration_path() intentionally rejects incompatible parent paths.
+ if len(iterator_nodes) != 1 or any(
+ not any(
+ source_edge.source.node_id == iterator_nodes[0]
+ or nx.has_path(iterator_graph, iterator_nodes[0], source_edge.source.node_id)
+ for source_edge in self._state.graph._get_input_edges(node_id, branch_field)
+ )
+ for branch_field in ("true_input", "false_input")
+ ):
+ return iter([[]])
+
+ if any(iterator_node_id not in self._state.source_prepared_mapping for iterator_node_id in iterator_nodes):
+ return iter([])
+ iterator_nodes_prepared = [
+ sorted(self._state.source_prepared_mapping[iterator_node_id], key=self._state._get_iteration_path)
+ for iterator_node_id in iterator_nodes
+ ]
+
+ if condition_edges:
+ condition_mappings = self._get_parent_iteration_mappings(node_id, graph, input_edges=condition_edges)
+ return iter(
+ condition_mapping + list(zip(iterator_nodes, prepared_iterators, strict=True))
+ for condition_mapping, prepared_iterators in zip(
+ condition_mappings, itertools.product(*iterator_nodes_prepared), strict=True
+ )
+ )
+
+ return iter(
+ [
+ list(zip(iterator_nodes, prepared_iterators, strict=True))
+ for prepared_iterators in itertools.product(*iterator_nodes_prepared)
+ ]
+ )
def _is_if_condition_ready(self, node_id: str) -> bool:
return all(
diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.py
index 6192e6e322..45dcec3a6f 100644
--- a/invokeai/app/services/shared/graph_validation.py
+++ b/invokeai/app/services/shared/graph_validation.py
@@ -4,6 +4,7 @@ import copy
import itertools
import sys
import weakref
+from contextvars import ContextVar
from dataclasses import dataclass
from functools import wraps
from typing import (
@@ -78,6 +79,8 @@ else:
NoneType = type(None)
+_ACTIVE_FACADE_OVERRIDES: ContextVar[frozenset[str]] = ContextVar("active_facade_overrides", default=frozenset())
+
# Port name constants
ITEM_FIELD = "item"
COLLECTION_FIELD = "collection"
@@ -93,7 +96,26 @@ def _get_facade_override(name: str, implementation: Callable[..., Any]) -> Calla
override = vars(facade).get(name)
if override is None or override is implementation:
return implementation
- return override
+
+ # A compatibility wrapper commonly saves the facade function and calls it from the override. In that case the
+ # saved function must execute its canonical body instead of rediscovering the wrapper. The extra frame check keeps
+ # the wrapper's side effects single-shot; the context guard covers callable overrides without a Python code object.
+ caller = sys._getframe(1)
+ override_code = getattr(override, "__code__", None)
+ if caller.f_back is not None and override_code is not None and caller.f_back.f_code is override_code:
+ return implementation
+ if name in _ACTIVE_FACADE_OVERRIDES.get():
+ return implementation
+
+ @wraps(override)
+ def dispatch(*args: Any, **kwargs: Any) -> Any:
+ token = _ACTIVE_FACADE_OVERRIDES.set(_ACTIVE_FACADE_OVERRIDES.get() | {name})
+ try:
+ return override(*args, **kwargs)
+ finally:
+ _ACTIVE_FACADE_OVERRIDES.reset(token)
+
+ return dispatch
@dataclass(frozen=True)
diff --git a/tests/app/services/session_processor/test_for_loop_processor_sqlite.py b/tests/app/services/session_processor/test_for_loop_processor_sqlite.py
index 1fef451396..786fae75b9 100644
--- a/tests/app/services/session_processor/test_for_loop_processor_sqlite.py
+++ b/tests/app/services/session_processor/test_for_loop_processor_sqlite.py
@@ -1017,11 +1017,12 @@ def test_processor_sqlite_two_sibling_nested_for_failure_cleans_runtime(
session = failed_item.session
assert session.execution_refs
assert all(
- session.execution_refs[execution_id] == execution_ref
+ session.execution_refs[execution_id].source_node_id == execution_ref.source_node_id
+ and session.execution_refs[execution_id].frame == execution_ref.frame
+ and session.execution_refs[execution_id].state_id == execution_ref.state_id
for execution_id, execution_ref in live_failed_session.execution_refs.items()
)
- assert session.execution_tokens
- assert set(live_failed_session.execution_tokens) <= set(session.execution_tokens)
+ assert session.execution_tokens == {}
assert session.execution_effects
assert set(live_failed_session.execution_effects) <= set(session.execution_effects)
assert session.has_error()
@@ -1106,8 +1107,8 @@ def test_processor_sqlite_three_level_nested_for_failure_cleans_runtime(
execution_refs_snapshot, execution_tokens_snapshot, execution_effects_snapshot, errors_snapshot = (
failed_persistence_snapshot
)
- assert execution_refs_snapshot
- assert execution_tokens_snapshot
+ assert execution_refs_snapshot == {}
+ assert execution_tokens_snapshot == {}
assert execution_effects_snapshot
failed_item = queue.get_queue_item(item_id)
@@ -1212,8 +1213,8 @@ def test_processor_sqlite_four_level_nested_for_failure_cleans_runtime(
execution_refs_snapshot, execution_tokens_snapshot, execution_effects_snapshot, errors_snapshot = (
failed_persistence_snapshot
)
- assert execution_refs_snapshot
- assert execution_tokens_snapshot
+ assert execution_refs_snapshot == {}
+ assert execution_tokens_snapshot == {}
assert execution_effects_snapshot
failed_item = queue.get_queue_item(item_id)
@@ -1260,7 +1261,7 @@ def test_processor_sqlite_four_level_nested_for_failure_cleans_runtime(
"deepest_return": (0, 0, 0, 0),
}
assert len(session.execution_refs) == 6
- assert len(session.execution_tokens) == 24
+ assert session.execution_tokens == {}
assert len(session.execution_effects) == 4
assert all(
reference.state_id == session.id
diff --git a/tests/app/services/shared/test_execution_effects.py b/tests/app/services/shared/test_execution_effects.py
index 44191b61ea..3ec2a2768e 100644
--- a/tests/app/services/shared/test_execution_effects.py
+++ b/tests/app/services/shared/test_execution_effects.py
@@ -1105,6 +1105,37 @@ def test_call_saved_workflow_declares_authorized_spawn_and_await_effects() -> No
assert effects[1].dependency.execution_node_id == effects[0].child_execution_id
+def test_call_saved_workflow_failure_effect_preserves_empty_message_exception() -> None:
+ class EmptyMessageError(Exception):
+ pass
+
+ def authorize_workflow(_workflow_id: str) -> object:
+ raise EmptyMessageError()
+
+ invocation = CallSavedWorkflowInvocation(id="call", workflow_id="workflow")
+ capability = ChildExecutionCapability(parent_execution_id="call", parent_frame=())
+ data = InvocationContextData(
+ queue_item=SimpleNamespace(user_id="user"),
+ invocation=invocation,
+ source_invocation_id="call",
+ execution_state_id="state",
+ execution_frame_id="frame",
+ execution_child_capability=capability,
+ execution_workflow_authorizer=authorize_workflow,
+ )
+ context = build_invocation_context(SimpleNamespace(), data, lambda: False)
+
+ invocation.invoke(context)
+
+ effects = context.execution_effects.snapshot()
+ assert len(effects) == 1
+ effect = effects[0]
+ assert isinstance(effect, FailEffect)
+ assert effect.message == ""
+ assert effect.error_type == "EmptyMessageError"
+ assert "EmptyMessageError" in (effect.error_traceback or "")
+
+
def test_capability_enabled_execution_interface_rejects_wrong_parent_scope() -> None:
capability = ChildExecutionCapability(parent_execution_id="other", parent_frame=())
recorder = ExecutionEffectsRecorder(
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 6d016b48ca..de6676e4f8 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -1579,7 +1579,7 @@ def _effect_ledger_projection(state: GraphExecutionState) -> tuple[Any, ...]:
def _execution_token_projection(state: GraphExecutionState) -> tuple[Any, ...]:
- """Project durable data tokens without generated execution identities."""
+ """Project durable activation tokens without generated execution identities."""
return tuple(
sorted(
(
@@ -1593,6 +1593,7 @@ def _execution_token_projection(state: GraphExecutionState) -> tuple[Any, ...]:
token.frame.workflow_call_depth,
)
for token in state.execution_tokens.values()
+ if token.token_kind == "activation"
),
key=repr,
)
@@ -1722,12 +1723,11 @@ def _direct_iterate_fan_in_execution_ref_projection(
state.prepared_source_mapping.get(exec_node_id, exec_node_id),
tuple(reference.frame.iteration_path),
reference.frame.workflow_call_depth,
- reference.effect_count,
)
for exec_node_id, reference in state.execution_refs.items()
if exec_node_id in state.prepared_source_mapping and (execution_ids is None or exec_node_id in execution_ids)
]
- return tuple(sorted(refs, key=lambda ref: (ref[0], ref[1], ref[2], ref[3] is not None, ref[3] or -1)))
+ return tuple(sorted(refs, key=lambda ref: (ref[0], ref[1], ref[2])))
def _source_edge_projection(graph: Graph) -> tuple[tuple[str, str, str, str, str], ...]:
@@ -5575,7 +5575,7 @@ def test_direct_iterate_body_collect_downstream_checkpoint_after_none_item_rehyd
assert _state_projection(resumed_state) == _state_projection(expected_state)
-def test_direct_flat_for_completion_persists_continuations_and_final_tokens() -> None:
+def test_direct_flat_for_completion_persists_continuations_and_result_outputs() -> None:
trace, state = _run(GraphExecutionState(graph=_flat_for_graph()))
assert trace == ["for", "body", "return", "for", "body", "return"]
@@ -5585,16 +5585,15 @@ def test_direct_flat_for_completion_persists_continuations_and_final_tokens() ->
state.source_prepared_mapping["for"],
key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,
)
- final_ref = state.execution_refs[final_for_id]
final_output = state.results[final_for_id]
- output_collection_token_id = f"{final_ref.reference_id}:output_collection"
- final_state_token_id = f"{final_ref.reference_id}:final_state"
assert snapshot["execution_effects"]
- assert state.execution_tokens[output_collection_token_id].value == final_output.output_collection == [11, 12]
- assert state.execution_tokens[final_state_token_id].value == final_output.final_state
- assert restored.execution_tokens[output_collection_token_id].value == [11, 12]
- assert restored.execution_tokens[final_state_token_id].value == final_output.final_state.model_dump(mode="json")
+ assert final_output.output_collection == [11, 12]
+ assert snapshot["execution_refs"] == {}
+ assert restored.execution_tokens == {}
+ assert restored.execution_refs
+ assert restored.results[final_for_id].output_collection == [11, 12]
+ assert restored.results[final_for_id].final_state == final_output.final_state
assert sorted(
(effect.operation, effect.continuation_kind)
for effects in state.execution_effects.values()
@@ -5772,9 +5771,8 @@ def test_flat_for_apply_partial_rehydration_preserves_continuation_runtime() ->
assert _effect_ledger_projection(restored) == _effect_ledger_projection(partial_state)
# Rehydration reconstructs references for all prepared nodes, while the partial in-memory
- # state only has references for nodes reached so far. Compare durable tokens/effects here;
- # resumed execution below compares the complete identity projection.
- assert _execution_identity_projection(restored)[1:] == _execution_identity_projection(partial_state)[1:]
+ # state only has references for nodes reached so far. Compare the durable token/effect projection.
+ assert _execution_token_projection(restored) == _execution_token_projection(partial_state)
_assert_execution_identity_consistent(restored)
assert any(
(effect.get("kind") if isinstance(effect, dict) else effect.kind) == "continuation"
@@ -5794,7 +5792,8 @@ def test_flat_for_apply_partial_rehydration_preserves_continuation_runtime() ->
assert _state_projection(resumed_state) == _state_projection(expected_state)
assert _continuation_projection(resumed_state) == _continuation_projection(expected_state)
assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)
- assert _execution_identity_projection(resumed_state) == _execution_identity_projection(expected_state)
+ assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)
+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)
assert _final_for_output(resumed_state).output_collection == [None, None]
_assert_execution_identity_consistent(resumed_state)
if force_compatibility_scheduler:
@@ -5884,17 +5883,23 @@ def test_flat_for_partial_rehydration_matches_compatibility_scheduler(stop_after
assert partial_trace + remaining_trace == expected_trace
assert _state_projection(resumed_state) == _state_projection(expected_state)
# Rehydration reconstructs durable execution references for all prepared nodes; a fresh
- # in-memory run does not retain those references after terminal cleanup. Compare the
- # durable token/effect portions directly and compare references across the two resumed
- # scheduler paths below.
- assert _execution_identity_projection(resumed_state)[1:] == _execution_identity_projection(expected_state)[1:]
+ # in-memory run does not retain those references after terminal cleanup. Compare durable
+ # token/effect state and continuation records instead.
+ assert _execution_token_projection(resumed_state) == _execution_token_projection(expected_state)
assert _continuation_projection(resumed_state) == _continuation_projection(expected_state)
+ assert _effect_ledger_projection(resumed_state) == _effect_ledger_projection(expected_state)
_assert_execution_identity_consistent(resumed_state)
if force_compatibility_scheduler:
assert isinstance(resumed_state._execution_scheduler, _ExecutionScheduler)
else:
assert isinstance(resumed_state._execution_scheduler, _GenericGraphSchedulerAdapter)
- resumed_projections.append((_state_projection(resumed_state), _execution_identity_projection(resumed_state)))
+ resumed_projections.append(
+ (
+ _state_projection(resumed_state),
+ _continuation_projection(resumed_state),
+ _effect_ledger_projection(resumed_state),
+ )
+ )
assert resumed_projections[0] == resumed_projections[1]
@@ -6342,8 +6347,10 @@ def test_fixture_is_versioned_and_future_versions_are_explicitly_rejected() -> N
with FIXTURE_PATH.open(encoding="utf-8") as fixture:
snapshot = json.load(fixture)
- assert snapshot["execution_state_version"] == CURRENT_EXECUTION_STATE_VERSION
- assert load_execution_state(snapshot).id == "fixture-state"
+ assert snapshot["execution_state_version"] == 1
+ restored = load_execution_state(snapshot)
+ assert restored.id == "fixture-state"
+ assert dump_execution_state(restored)["execution_state_version"] == CURRENT_EXECUTION_STATE_VERSION
future_snapshot = dict(snapshot)
future_snapshot["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSION + 1
@@ -6924,6 +6931,164 @@ def test_fresh_mixed_iterate_if_collect_uses_selected_branches_in_both_scheduler
assert _state_projection(runs[0][1]) == _state_projection(runs[1][1])
[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])
+def test_constant_if_inside_iterate_routes_each_loop_item(condition: bool, branch: str) -> None:
+ graph = Graph()
+ graph.add_node(CollectionConcatInvocation(id="source", first=[1, 2]))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(IfInvocation(id="if", condition=condition))
+ graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))
+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "true_branch", "value"))
+ graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))
+ graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))
+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))
+ graph.add_edge(create_edge("if", "value", "collect", "item"))
+
+ trace, state = _run_graph(GraphExecutionState(graph=graph))
+
+ selected_source = "true_branch" if condition else "false_branch"
+ unselected_source = "false_branch" if condition else "true_branch"
+ assert trace[0] == "source"
+ assert trace[-1] == "collect"
+ assert trace.count("iterate") == 2
+ assert trace.count(selected_source) == 2
+ assert trace.count("if") == 2
+ assert unselected_source not in trace
+ collect_id = next(iter(state.source_prepared_mapping["collect"]))
+ assert state.results[collect_id].collection == [f"{branch}1", f"{branch}2"]
+ assert state.is_complete()
+ assert state.next() is None
+ assert not state._ready_node_ids
+ assert all(not queue for queue in state._ready_queues.values())
+
+
[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])
+def test_constant_if_inside_for_routes_each_loop_item(condition: bool, branch: str) -> None:
+ graph = Graph()
+ graph.add_node(ForInvocation(id="for", collection=[1, 2]))
+ graph.add_node(IfInvocation(id="if", condition=condition))
+ graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))
+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))
+ graph.add_node(ForReturnInvocation(id="return"))
+ graph.add_edge(create_edge("for", "item", "true_branch", "value"))
+ graph.add_edge(create_edge("for", "item", "false_branch", "value"))
+ graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))
+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))
+ graph.add_edge(create_edge("if", "value", "return", "output"))
+ graph.add_edge(create_loop_linkage("for", "return"))
+
+ trace, state = _run_graph(GraphExecutionState(graph=graph))
+
+ selected_source = "true_branch" if condition else "false_branch"
+ unselected_source = "false_branch" if condition else "true_branch"
+ assert trace.count("for") == 2
+ assert trace.count(selected_source) == 2
+ assert trace.count("if") == 2
+ assert trace.count("return") == 2
+ assert unselected_source not in trace
+ assert sorted(state._get_iteration_path(exec_node_id) for exec_node_id in state.source_prepared_mapping["if"]) == [
+ (0,),
+ (1,),
+ ]
+ final_for_id = max(
+ state.source_prepared_mapping["for"],
+ key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,
+ )
+ assert state.results[final_for_id].output_collection == [f"{branch}1", f"{branch}2"]
+ assert state.is_complete()
+ assert state.next() is None
+ assert not state._ready_node_ids
+ assert all(not queue for queue in state._ready_queues.values())
+
+
[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])
+def test_external_condition_if_inside_iterate_routes_each_loop_item(condition: bool, branch: str) -> None:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="condition", value=condition))
+ graph.add_node(CollectionConcatInvocation(id="source", first=[1, 2]))
+ graph.add_node(IterateInvocation(id="iterate"))
+ graph.add_node(IfInvocation(id="if"))
+ graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))
+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))
+ graph.add_node(CollectInvocation(id="collect"))
+ graph.add_edge(create_edge("condition", "value", "if", "condition"))
+ graph.add_edge(create_edge("source", "collection", "iterate", "collection"))
+ graph.add_edge(create_edge("iterate", "item", "true_branch", "value"))
+ graph.add_edge(create_edge("iterate", "item", "false_branch", "value"))
+ graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))
+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))
+ graph.add_edge(create_edge("if", "value", "collect", "item"))
+
+ trace, state = _run_graph(GraphExecutionState(graph=graph))
+
+ selected_source = "true_branch" if condition else "false_branch"
+ unselected_source = "false_branch" if condition else "true_branch"
+ assert trace.count("condition") == 1
+ assert trace.count("source") == 1
+ assert trace.count("iterate") == 2
+ assert trace.count(selected_source) == 2
+ assert trace.count("if") == 2
+ assert trace.count("collect") == 1
+ assert unselected_source not in trace
+ assert sorted(state._get_iteration_path(exec_node_id) for exec_node_id in state.source_prepared_mapping["if"]) == [
+ (0,),
+ (1,),
+ ]
+ collect_id = next(iter(state.source_prepared_mapping["collect"]))
+ assert state.results[collect_id].collection == [f"{branch}1", f"{branch}2"]
+ assert state.is_complete()
+ assert state.next() is None
+ assert not state._pending_if_exec_nodes
+ assert not state._ready_node_ids
+ assert all(not queue for queue in state._ready_queues.values())
+
+
[email protected](("condition", "branch"), [(True, "true:"), (False, "false:")])
+def test_external_condition_if_inside_for_routes_each_loop_item(condition: bool, branch: str) -> None:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="condition", value=condition))
+ graph.add_node(ForInvocation(id="for", collection=[1, 2]))
+ graph.add_node(IfInvocation(id="if"))
+ graph.add_node(MarkedAnyTypeTestInvocation(id="true_branch", marker="true:"))
+ graph.add_node(MarkedAnyTypeTestInvocation(id="false_branch", marker="false:"))
+ graph.add_node(ForReturnInvocation(id="return"))
+ graph.add_edge(create_edge("condition", "value", "if", "condition"))
+ graph.add_edge(create_edge("for", "item", "true_branch", "value"))
+ graph.add_edge(create_edge("for", "item", "false_branch", "value"))
+ graph.add_edge(create_edge("true_branch", "value", "if", "true_input"))
+ graph.add_edge(create_edge("false_branch", "value", "if", "false_input"))
+ graph.add_edge(create_edge("if", "value", "return", "output"))
+ graph.add_edge(create_loop_linkage("for", "return"))
+
+ trace, state = _run_graph(GraphExecutionState(graph=graph))
+
+ selected_source = "true_branch" if condition else "false_branch"
+ unselected_source = "false_branch" if condition else "true_branch"
+ assert trace.count("condition") == 1
+ assert trace.count("for") == 2
+ assert trace.count(selected_source) == 2
+ assert trace.count("if") == 2
+ assert trace.count("return") == 2
+ assert unselected_source not in trace
+ assert sorted(state._get_iteration_path(exec_node_id) for exec_node_id in state.source_prepared_mapping["if"]) == [
+ (0,),
+ (1,),
+ ]
+ final_for_id = max(
+ state.source_prepared_mapping["for"],
+ key=lambda exec_node_id: state.execution_graph.get_node(exec_node_id).index,
+ )
+ assert state.results[final_for_id].output_collection == [f"{branch}1", f"{branch}2"]
+ assert state.is_complete()
+ assert state.next() is None
+ assert not state._pending_if_exec_nodes
+ assert not state._ready_node_ids
+ assert all(not queue for queue in state._ready_queues.values())
+
+
@pytest.mark.parametrize("force_compatibility_scheduler", [False, True])
@pytest.mark.parametrize(
("first_condition", "second_condition", "third_condition"),
diff --git a/tests/app/services/shared/test_execution_engine_scheduler.py b/tests/app/services/shared/test_execution_engine_scheduler.py
index dfe8fb7c13..aa335d26dd 100644
--- a/tests/app/services/shared/test_execution_engine_scheduler.py
+++ b/tests/app/services/shared/test_execution_engine_scheduler.py
@@ -905,3 +905,70 @@ def test_graph_state_apply_rolls_back_generic_scheduler_transition() -> None:
state._record_effect_streams = original_record_effect_streams # type: ignore[method-assign]
assert state.executed == set()
+
+
+def test_graph_state_apply_retry_after_if_branch_failure_completes_graph() -> None:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="condition", value=True))
+ graph.add_node(AddInvocation(id="true_value", a=1, b=2))
+ graph.add_node(AddInvocation(id="false_value", a=3, b=4))
+ graph.add_node(IfInvocation(id="if"))
+ graph.add_node(AddInvocation(id="consumer", b=10))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="condition", field="value"),
+ destination=EdgeConnection(node_id="if", field="condition"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="true_value", field="value"),
+ destination=EdgeConnection(node_id="if", field="true_input"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="false_value", field="value"),
+ destination=EdgeConnection(node_id="if", field="false_input"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="if", field="value"),
+ destination=EdgeConnection(node_id="consumer", field="a"),
+ )
+ )
+
+ state = GraphExecutionState(graph=graph)
+ branch_node = None
+ while (node := state.next()) is not None:
+ source_node_id = state.prepared_source_mapping[node.id]
+ if source_node_id == "true_value":
+ branch_node = node
+ break
+ state.complete(node.id, node.invoke(Mock()))
+ assert branch_node is not None
+
+ execution_ref = state.get_execution_ref(branch_node.id)
+ output = branch_node.invoke(Mock())
+ original_record_effect_streams = state._record_effect_streams
+
+ def fail_after_scheduler_mutation(*args: object, **kwargs: object) -> None:
+ raise RuntimeError("effect recording failed")
+
+ state._record_effect_streams = fail_after_scheduler_mutation # type: ignore[method-assign]
+ try:
+ with pytest.raises(RuntimeError, match="effect recording failed"):
+ state.apply(execution_ref, output)
+ finally:
+ state._record_effect_streams = original_record_effect_streams # type: ignore[method-assign]
+
+ assert branch_node.id not in state.executed
+
+ state.apply(execution_ref, output)
+ while (node := state.next()) is not None:
+ state.complete(node.id, node.invoke(Mock()))
+
+ consumer_exec_id = next(iter(state.source_prepared_mapping["consumer"]))
+ assert state.results[consumer_exec_id].value == 13
+ assert state.is_complete()
diff --git a/tests/app/services/shared/test_execution_state_migration.py b/tests/app/services/shared/test_execution_state_migration.py
index 8aded3980b..7be28a0435 100644
--- a/tests/app/services/shared/test_execution_state_migration.py
+++ b/tests/app/services/shared/test_execution_state_migration.py
@@ -1,6 +1,18 @@
+import json
+
import pytest
+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
+from invokeai.app.invocations.collections import RangeInvocation
from invokeai.app.invocations.math import AddInvocation
+from invokeai.app.invocations.primitives import IntegerCollectionOutput
+from invokeai.app.services.shared.execution_effects import (
+ AwaitEffect,
+ SpawnExecutionEffect,
+)
+from invokeai.app.services.shared.execution_effects import (
+ ExecutionRef as EffectExecutionRef,
+)
from invokeai.app.services.shared.execution_state_migration import (
CURRENT_EXECUTION_STATE_VERSION,
UnsupportedExecutionStateVersionError,
@@ -8,12 +20,16 @@ from invokeai.app.services.shared.execution_state_migration import (
load_execution_state,
)
from invokeai.app.services.shared.graph import (
+ Edge,
+ EdgeConnection,
ExecutionFrame,
ExecutionReference,
ExecutionToken,
Graph,
GraphExecutionState,
+ IterateInvocation,
)
+from invokeai.app.services.shared.graph_validation import IterateInvocationOutput
def _make_state() -> GraphExecutionState:
@@ -122,10 +138,10 @@ def test_round_trips_nullable_execution_token_value() -> None:
state.execution_tokens["token-id"] = token
snapshot = dump_execution_state(state)
- assert snapshot["execution_tokens"]["token-id"]["value"] is None
+ assert snapshot["execution_tokens"] == {}
restored = load_execution_state(snapshot)
- assert restored.execution_tokens["token-id"].value is None
+ assert restored.execution_tokens == {}
def test_round_trips_nullable_execution_token_value_in_child_state() -> None:
@@ -143,11 +159,11 @@ def test_round_trips_nullable_execution_token_value_in_child_state() -> None:
snapshot = dump_execution_state(state)
child_snapshot = snapshot["waiting_workflow_call_child_session"]
- assert child_snapshot["execution_tokens"]["token-id"]["value"] is None
+ assert child_snapshot["execution_tokens"] == {}
restored = load_execution_state(snapshot)
assert restored.waiting_workflow_call_child_session is not None
- assert restored.waiting_workflow_call_child_session.execution_tokens["token-id"].value is None
+ assert restored.waiting_workflow_call_child_session.execution_tokens == {}
def test_internal_execution_fields_are_persisted_but_not_publicly_serialized() -> None:
@@ -202,8 +218,8 @@ def test_internal_execution_fields_are_persisted_but_not_publicly_serialized() -
}.isdisjoint(public_model_dump)
persisted_payload = dump_execution_state(state)
- assert persisted_payload["execution_refs"]["exec-node"]["reference_id"] == execution_ref.reference_id
- assert persisted_payload["execution_tokens"]["token-id"]["value"] == 3
+ assert persisted_payload["execution_refs"] == {}
+ assert persisted_payload["execution_tokens"] == {}
assert persisted_payload["execution_effects"] == {}
@@ -226,3 +242,169 @@ def test_round_trips_pending_generic_child_dependency_and_partial_completion() -
assert dependency.enqueue_order == ["20", "10"]
assert dependency.completed_child_execution_ids == ["10"]
assert dependency.completions["10"].outputs == {"value": "ten"}
+
+
+def _make_completed_iterate_state(iteration_count: int = 2) -> GraphExecutionState:
+ graph = Graph()
+ graph.add_node(RangeInvocation(id="range", start=0, stop=iteration_count, step=1))
+ graph.add_node(IterateInvocation(id="iterate", collection=list(range(iteration_count))))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="range", field="collection"),
+ destination=EdgeConnection(node_id="iterate", field="collection"),
+ )
+ )
+ execution_graph = Graph()
+ prepared_source_mapping: dict[str, str] = {"range-exec": "range"}
+ source_prepared_mapping = {"range": {"range-exec"}, "iterate": set()}
+ prepared_iteration_paths: dict[str, tuple[int, ...]] = {}
+ results = {"range-exec": IntegerCollectionOutput(collection=list(range(iteration_count)))}
+ executed = {"range-exec"}
+ execution_graph.add_node(RangeInvocation(id="range-exec", start=0, stop=iteration_count, step=1))
+ for index in range(iteration_count):
+ exec_node_id = f"iterate-{index}"
+ execution_graph.add_node(
+ IterateInvocation(id=exec_node_id, collection=list(range(iteration_count)), index=index)
+ )
+ prepared_source_mapping[exec_node_id] = "iterate"
+ source_prepared_mapping["iterate"].add(exec_node_id)
+ prepared_iteration_paths[exec_node_id] = (index,)
+ results[exec_node_id] = IterateInvocationOutput(item=index, index=index, total=iteration_count)
+ executed.add(exec_node_id)
+
+ state = GraphExecutionState(
+ graph=graph,
+ execution_graph=execution_graph,
+ executed=executed,
+ results=results,
+ prepared_source_mapping=prepared_source_mapping,
+ source_prepared_mapping=source_prepared_mapping,
+ prepared_iteration_paths=prepared_iteration_paths,
+ )
+ for exec_node_id in prepared_source_mapping:
+ reference = state.get_execution_ref(exec_node_id)
+ iterate_output = results.get(exec_node_id)
+ if not isinstance(iterate_output, IterateInvocationOutput):
+ continue
+ state.execution_tokens[f"{reference.reference_id}:item"] = ExecutionToken(
+ token_id=f"{reference.reference_id}:item",
+ reference_id=reference.reference_id,
+ owner_node_id=exec_node_id,
+ port="item",
+ frame=reference.frame,
+ value=iterate_output.item,
+ )
+ effects = [
+ {
+ "kind": "emit",
+ "token": {
+ "node_id": exec_node_id,
+ "field": "item",
+ "value": iterate_output.item,
+ "sequence": iterate_output.index,
+ },
+ "value": iterate_output.item,
+ }
+ ]
+ if iterate_output.index + 1 >= iterate_output.total:
+ effects.append(
+ {
+ "kind": "close_stream",
+ "token": {
+ "node_id": exec_node_id,
+ "field": "item",
+ "token_kind": "stream_end",
+ "sequence": iteration_count,
+ },
+ }
+ )
+ state.execution_effects[reference.reference_id] = effects
+ return state
+
+
+def test_compact_iterate_ledgers_have_deterministic_record_bound_and_rehydrate() -> None:
+ snapshot = dump_execution_state(_make_completed_iterate_state())
+
+ assert snapshot["execution_refs"] == {}
+ assert sum(len(effects) for effects in snapshot["execution_effects"].values()) == 3
+ assert snapshot["execution_tokens"] == {}
+ assert len(json.dumps(snapshot, sort_keys=True, separators=(",", ":"))) < 5000
+
+ restored = load_execution_state(snapshot)
+
+ stream = next(iter(restored._generic_runtime().streams.values()))
+ assert stream.values == (0, 1)
+ assert stream.closed
+ assert restored.is_complete()
+
+
+def test_completed_workflow_call_snapshot_does_not_retain_child_graph() -> None:
+ graph = Graph()
+ graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="saved"))
+ parent = GraphExecutionState(graph=graph)
+ call = parent.next()
+ assert call is not None
+ frame = parent.build_workflow_call_frame(call.id, "saved")
+ parent.begin_waiting_on_workflow_call(frame)
+ child_graph = Graph()
+ child_graph.add_node(AddInvocation(id="child-node", a=1, b=2))
+ child = GraphExecutionState(graph=child_graph)
+ parent.attach_waiting_workflow_call_child_session(child)
+ execution_ref = parent._expected_execution_ref(call.id)
+ parent.execution_refs[call.id] = execution_ref
+ parent.execution_effects[execution_ref.reference_id] = [
+ SpawnExecutionEffect(
+ parent=EffectExecutionRef(
+ execution_node_id=call.id,
+ state_id=parent.id,
+ frame_path=execution_ref.frame.iteration_path,
+ frame_id=execution_ref.frame.frame_id,
+ workflow_call_depth=execution_ref.frame.workflow_call_depth,
+ ),
+ graph=child.graph.model_dump(mode="json"),
+ child_execution_id=child.id,
+ ),
+ AwaitEffect(
+ dependency=EffectExecutionRef(
+ execution_node_id=call.id,
+ state_id=parent.id,
+ frame_path=execution_ref.frame.iteration_path,
+ frame_id=execution_ref.frame.frame_id,
+ workflow_call_depth=execution_ref.frame.workflow_call_depth,
+ )
+ ),
+ ]
+ parent.end_waiting_on_workflow_call()
+ parent.executed.add(call.id)
+
+ snapshot = dump_execution_state(parent)
+
+ assert "waiting_workflow_call_child_session" not in snapshot
+ assert snapshot["workflow_call_history"][0]["child_session_id"] == child.id
+ assert execution_ref.reference_id not in snapshot["execution_effects"]
+
+ active_parent = GraphExecutionState(graph=parent.graph.model_copy(deep=True))
+ active_call = active_parent.next()
+ assert active_call is not None
+ active_frame = active_parent.build_workflow_call_frame(active_call.id, "saved")
+ active_parent.begin_waiting_on_workflow_call(active_frame)
+ active_child = GraphExecutionState(graph=child_graph.model_copy(deep=True))
+ active_parent.attach_waiting_workflow_call_child_session(active_child)
+ active_ref = active_parent._expected_execution_ref(active_call.id)
+ active_parent.execution_refs[active_call.id] = active_ref
+ active_parent.execution_effects[active_ref.reference_id] = [
+ SpawnExecutionEffect(
+ parent=EffectExecutionRef(
+ execution_node_id=active_call.id,
+ state_id=active_parent.id,
+ frame_path=active_ref.frame.iteration_path,
+ frame_id=active_ref.frame.frame_id,
+ workflow_call_depth=active_ref.frame.workflow_call_depth,
+ ),
+ graph=active_child.graph.model_dump(mode="json"),
+ child_execution_id=active_child.id,
+ )
+ ]
+ active_snapshot = dump_execution_state(active_parent)
+ assert active_ref.reference_id in active_snapshot["execution_effects"]
+ assert "waiting_workflow_call_child_session" in active_snapshot
diff --git a/tests/app/services/shared/test_for_scheduler_performance.py b/tests/app/services/shared/test_for_scheduler_performance.py
index a28d4eca6a..dd8445f9ab 100644
--- a/tests/app/services/shared/test_for_scheduler_performance.py
+++ b/tests/app/services/shared/test_for_scheduler_performance.py
@@ -12,8 +12,16 @@ from unittest.mock import Mock
import pytest
from invokeai.app.invocations.collections import RangeInvocation
+from invokeai.app.invocations.logic import IfInvocation
from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation
-from invokeai.app.services.shared.graph import CollectInvocation, Graph, GraphExecutionState, IterateInvocation
+from invokeai.app.invocations.primitives import BooleanInvocation
+from invokeai.app.services.shared.graph import (
+ CollectInvocation,
+ Graph,
+ GraphExecutionState,
+ IterateInvocation,
+ _GenericGraphSchedulerAdapter,
+)
from tests.test_nodes import AnyTypeTestInvocation, create_edge, create_loop_linkage
@@ -56,6 +64,18 @@ class _CountingMapping(dict[str, object]):
self._counter.record(self._mapping_name)
yield key
+ def __contains__(self, key: object) -> bool:
+ self._counter.record(self._mapping_name)
+ return super().__contains__(key)
+
+ def __getitem__(self, key: str) -> object:
+ self._counter.record(self._mapping_name)
+ return super().__getitem__(key)
+
+ def get(self, key: str, default: object = None) -> object: # type: ignore[override]
+ self._counter.record(self._mapping_name)
+ return super().get(key, default)
+
def _run_trivial_loop(
loop_type: str,
@@ -63,25 +83,47 @@ def _run_trivial_loop(
*,
clock: Callable[[], float] = time.process_time,
mapping_counter: _MappingTraversalCounter | None = None,
+ include_if: bool = False,
+ external_condition: bool = False,
) -> float:
graph = Graph()
graph.add_node(RangeInvocation(id="range", start=0, stop=count))
graph.add_node(ForInvocation(id="loop") if loop_type == "for" else IterateInvocation(id="loop"))
- graph.add_node(AnyTypeTestInvocation(id="body"))
graph.add_edge(create_edge("range", "collection", "loop", "collection"))
- graph.add_edge(create_edge("loop", "item", "body", "value"))
+ if include_if:
+ graph.add_node(AnyTypeTestInvocation(id="true_body"))
+ graph.add_node(AnyTypeTestInvocation(id="false_body"))
+ graph.add_node(IfInvocation(id="if") if external_condition else IfInvocation(id="if", condition=True))
+ if external_condition:
+ graph.add_node(BooleanInvocation(id="condition", value=True))
+ graph.add_edge(create_edge("condition", "value", "if", "condition"))
+ graph.add_edge(create_edge("loop", "item", "true_body", "value"))
+ graph.add_edge(create_edge("loop", "item", "false_body", "value"))
+ graph.add_edge(create_edge("true_body", "value", "if", "true_input"))
+ graph.add_edge(create_edge("false_body", "value", "if", "false_input"))
+ output_source = "if"
+ else:
+ graph.add_node(AnyTypeTestInvocation(id="body"))
+ graph.add_edge(create_edge("loop", "item", "body", "value"))
+ output_source = "body"
if loop_type == "for":
graph.add_node(ForReturnInvocation(id="return"))
- graph.add_edge(create_edge("body", "value", "return", "output"))
+ graph.add_edge(create_edge(output_source, "value", "return", "output"))
graph.add_edge(create_loop_linkage("loop", "return"))
else:
graph.add_node(CollectInvocation(id="collect"))
- graph.add_edge(create_edge("body", "value", "collect", "item"))
+ graph.add_edge(create_edge(output_source, "value", "collect", "item"))
state = GraphExecutionState(graph=graph)
if mapping_counter is not None:
- state._scheduler()
- state.execution_effects = _CountingMapping(state.execution_effects, mapping_counter, "execution_effects")
- state.results = _CountingMapping(state.results, mapping_counter, "results")
+ scheduler = state._scheduler()
+ state.execution_refs = _CountingMapping(state.execution_refs, mapping_counter, "execution_refs") # type: ignore[assignment]
+ state.execution_tokens = _CountingMapping(state.execution_tokens, mapping_counter, "execution_tokens") # type: ignore[assignment]
+ state.execution_effects = _CountingMapping(state.execution_effects, mapping_counter, "execution_effects") # type: ignore[assignment]
+ state.results = _CountingMapping(state.results, mapping_counter, "results") # type: ignore[assignment]
+ if isinstance(scheduler, _GenericGraphSchedulerAdapter):
+ scheduler._scheduler.plan.nodes = _CountingMapping(
+ scheduler._scheduler.plan.nodes, mapping_counter, "scheduler_plan"
+ )
context = Mock()
started = clock()
while (node := state.next()) is not None:
@@ -90,21 +132,40 @@ def _run_trivial_loop(
return clock() - started
[email protected]("loop_type", ["iterate", "for"])
-def test_loop_scheduler_does_not_rescan_growing_state(loop_type: str) -> None:
+ ("loop_type", "include_if", "external_condition"),
+ [
+ ("iterate", False, False),
+ ("for", False, False),
+ ("iterate", True, False),
+ ("iterate", True, True),
+ ("for", True, False),
+ ("for", True, True),
+ ],
+)
+def test_loop_scheduler_does_not_rescan_growing_state(
+ loop_type: str, include_if: bool, external_condition: bool
+) -> None:
visits: dict[int, int] = {}
visits_by_mapping: dict[int, dict[str, int]] = {}
for count in (300, 1200):
counter = _MappingTraversalCounter()
- _run_trivial_loop(loop_type, count, mapping_counter=counter)
+ _run_trivial_loop(
+ loop_type,
+ count,
+ mapping_counter=counter,
+ include_if=include_if,
+ external_condition=external_condition,
+ )
visits[count] = counter.entries_visited
visits_by_mapping[count] = counter.visits_by_mapping
# A small constant number of full mapping passes is acceptable. A pass per iteration is not:
# it visits growing scheduler state quadratically. For covers durable effect history; Iterate covers
# result synchronization in the generic scheduler.
- assert all(visits[count] <= count * 32 for count in visits), (
- f"mapping visits for {loop_type}: {visits}; by mapping: {visits_by_mapping}"
+ assert all(visits[count] <= count * 128 for count in visits), (
+ f"mapping visits for {loop_type}, include_if={include_if}, external_condition={external_condition}: "
+ f"{visits}; by mapping: {visits_by_mapping}"
)
diff --git a/tests/app/services/shared/test_graph_if_runtime.py b/tests/app/services/shared/test_graph_if_runtime.py
index 5664df7c69..2ff72717bf 100644
--- a/tests/app/services/shared/test_graph_if_runtime.py
+++ b/tests/app/services/shared/test_graph_if_runtime.py
@@ -1,8 +1,9 @@
import pytest
from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.invocations.math import AddInvocation
from invokeai.app.services.shared.execution_engine.scheduler import ActivationDependency
-from invokeai.app.services.shared.graph import Graph, GraphExecutionState
+from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph, GraphExecutionState
from invokeai.app.services.shared.graph_runtime_records import _ApplyTransaction
from tests.app.services.shared.import_test_utils import assert_module_imports_without_graph
@@ -87,3 +88,18 @@ def test_activation_resolution_and_token_are_idempotent_and_rollback(state: Grap
assert state._activation_gate("if-exec").model_dump() == gate_before
assert state.execution_tokens == {}
assert "if-exec" not in state._if_activation_dependencies_by_exec
+
+
+def test_apply_rollback_reconstructs_pending_if_nodes(state: GraphExecutionState) -> None:
+ state.graph.add_node(AddInvocation(id="source", a=1, b=2))
+ state.graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="source", field="value"),
+ destination=EdgeConnection(node_id="if", field="true_input"),
+ )
+ )
+ state._resolved_if_exec_branches["if-exec"] = "true_input"
+
+ state._reset_apply_derived_caches()
+
+ assert state._pending_if_exec_nodes == {"if-exec"}
diff --git a/tests/app/services/shared/test_graph_models.py b/tests/app/services/shared/test_graph_models.py
index 50c56d4979..f6211956c8 100644
--- a/tests/app/services/shared/test_graph_models.py
+++ b/tests/app/services/shared/test_graph_models.py
@@ -100,6 +100,23 @@ def test_graph_facade_preserves_authoring_helper_patch_points(monkeypatch: pytes
assert not graph_facade.are_connections_compatible(source, "value", destination, "a")
+def test_graph_facade_override_can_delegate_to_saved_original(monkeypatch: pytest.MonkeyPatch) -> None:
+ source = AddInvocation(id="source", a=1, b=2)
+ destination = AddInvocation(id="destination", a=3, b=4)
+ original = graph_facade.are_connections_compatible
+ calls = 0
+
+ def wrapped(*args: object, **kwargs: object) -> bool:
+ nonlocal calls
+ calls += 1
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(graph_facade, "are_connections_compatible", wrapped)
+
+ assert graph_facade.are_connections_compatible(source, "value", destination, "a")
+ assert calls == 1
+
+
def test_graph_facade_reexports_graph_models() -> None:
exported_names = (
"EdgeConnection",
diff --git a/tests/app/services/test_workflow_call_runtime.py b/tests/app/services/test_workflow_call_runtime.py
index fa309f1666..fbfc4b1b14 100644
--- a/tests/app/services/test_workflow_call_runtime.py
+++ b/tests/app/services/test_workflow_call_runtime.py
@@ -9,6 +9,10 @@ def test_run_node_persists_saved_workflow_lifecycle_effects_before_queue_dispatc
workflow_call_tests.test_run_node_persists_saved_workflow_lifecycle_effects_before_queue_dispatch(monkeypatch)
+def test_run_node_preserves_saved_workflow_failure_metadata(monkeypatch) -> None:
+ workflow_call_tests.test_run_node_preserves_saved_workflow_failure_metadata(monkeypatch)
+
+
def test_run_persists_waiting_session_without_completing_queue_item(monkeypatch) -> None:
workflow_call_tests.test_run_persists_waiting_session_without_completing_queue_item(monkeypatch)
diff --git a/tests/app/services/workflow_call_test_utils.py b/tests/app/services/workflow_call_test_utils.py
index 7e74511a2a..b3248ffc1b 100644
--- a/tests/app/services/workflow_call_test_utils.py
+++ b/tests/app/services/workflow_call_test_utils.py
@@ -1476,6 +1476,47 @@ def test_run_node_persists_saved_workflow_lifecycle_effects_before_queue_dispatc
assert events.completed == []
+def test_run_node_preserves_saved_workflow_failure_metadata(monkeypatch: pytest.MonkeyPatch) -> None:
+ class EmptyWorkflowError(Exception):
+ pass
+
+ session_queue = _DummySessionQueue()
+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)
+
+ def fail_validation(self, context):
+ raise EmptyWorkflowError()
+
+ monkeypatch.setattr(CallSavedWorkflowInvocation, "validate_selected_workflow", fail_validation)
+ graph = Graph()
+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))
+ session = GraphExecutionState(graph=graph)
+ invocation = session.next()
+ assert isinstance(invocation, CallSavedWorkflowInvocation)
+ queue_item = type(
+ "QueueItem",
+ (),
+ {
+ "item_id": 1,
+ "status": "in_progress",
+ "session": session,
+ "session_id": session.id,
+ "user_id": "user-1",
+ "queue_id": "default",
+ "batch_id": "batch-1",
+ },
+ )()
+
+ session_queue.add_queue_item(queue_item)
+ runner.run_node(invocation=invocation, queue_item=queue_item)
+
+ assert session_queue.failed_item_ids == [1]
+ assert len(events.errors) == 1
+ _queue_item, _invocation, error_type, error_message, error_traceback = events.errors[0]
+ assert error_type == "EmptyWorkflowError"
+ assert error_message == ""
+ assert "EmptyWorkflowError" in error_traceback
+
+
def test_run_node_fails_cleanly_for_invalid_batch_child_workflow(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index ef71c5ba77..b0f4fdc935 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -269,7 +269,7 @@ def test_graph_state_apply_stores_stable_frame_tokens_and_effects():
restored = load_execution_state(dump_execution_state(state))
assert restored.get_execution_ref(node.id).reference_id == ref.reference_id
- assert restored.execution_tokens[f"{ref.reference_id}:value"].frame == ref.frame
+ assert restored.execution_tokens == {}
def test_graph_state_apply_accepts_protocol_ref_without_token():