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.

test(execution): prove If cancellation and retry safety

JPPhoto5f0fd2b183c6
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 1281635858..8e5ac41135 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -195,7 +195,10 @@ suppresses effects: effect-enabled invocations bypass the ordinary output cache
`IfInvocation` is the first control-flow invocation to declare an activation-effect contract. It emits one
frame-scoped activation token for the selected `true_input` or `false_input` port; `GraphExecutionState` validates that
-port against the producing invocation's declared activation fields and persists it without creating a data stream.
+port against the producing invocation's declared activation fields and persists it without creating a data stream. On
+rehydration, every activation token is bound to a currently prepared owner and its derived execution reference; its
+declared port, value, canonical token id, mapping key, and known frame fields must match. Unknown extra frame metadata
+remains forward-compatible.
The generic plan stores opaque, frame-local activation-dependency records for `If` branch-local nodes. Its readiness
callback accepts a node only when the required private `ActivationGate` runtime state is resolved and a matching
persisted activation token is present for its frame; the activation token is therefore authoritative for generic
@@ -252,7 +255,12 @@ propagation must not leave stale downstream indegrees. Both scheduler adapters
expose the same skip transition; the legacy path releases downstream indegrees
without trying to hydrate inputs from the skipped node. It intentionally does
not claim durable persistence of the generic scheduler's private claim set, nor
-does it cover loop or workflow-call ownership migration.
+does it cover loop or workflow-call ownership migration. Real queue/processor
+coverage in `tests/app/services/session_processor/test_if_processor_sqlite.py`
+also exercises true and false `If` selection, cancellation before and after
+resolution, retry from a canceled SQLite item, fresh execution identities, and
+selected-only completion. Stale identity and legacy loop-frame rehydration are
+covered separately by the differential and graph-state tests.
Workflow-call note:
@@ -318,10 +326,12 @@ JSON/model round trip. Rehydration reconstructs prepared exec metadata, cached i
gate state from condition results or persisted 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`. Activation tokens persist; private `ActivationGate` runtime state does not and is
-reconstructed from condition results or persisted activation tokens. Persisted execution references, tokens, and effects
-remain part of serialized state; private helper objects do not. Queue snapshots carry an additive execution-state version
-marker and use version-aware loader; legacy unmarked snapshots are treated as version 0, while unreadable snapshots are
-quarantined by queue service.
+reconstructed from condition results or persisted activation tokens. 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. Persisted execution references, tokens, and effects remain part of serialized state; private
+helper objects do not. Queue snapshots carry an additive execution-state version marker and use version-aware loader;
+legacy unmarked snapshots are treated as version 0, while unreadable snapshots are quarantined by queue service.
### 4.4 Preparation (`_prepare()`)
@@ -405,6 +415,9 @@ Run `C` -> `D:0` -> enqueue `D`. Run `D` -> done.
- In forced compatibility `_ExecutionScheduler` scheduling, `_IfBranchScheduler` retains legacy behavior: selected work
is released, unselected work is marked skipped, unselected input edges on the prepared `If` exec node are pruned, and
branch-exclusive ancestors of the unselected branch are never executed.
+- The SQLite queue/processor path has evidence for cancellation before and after `If` resolution and retry from each
+ boundary for both condition polarities. A canceled attempt keeps its activation ledger and cannot resume; retry starts
+ a fresh state and must emit a fresh matching activation token before selected-only completion.
- Retired or skipped branch-local exec nodes may still be treated as executed for scheduling purposes, but they do not
create entries in `results`.
- Shared ancestors still execute if they are required by the selected branch or by any other live path in the graph.
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index aa9afa96cc..e5e529e073 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -5798,7 +5798,39 @@ class GraphExecutionState(BaseModel):
)
return True
+ def _validate_persisted_activation_tokens(self) -> None:
+ for token_key, token in self.execution_tokens.items():
+ if token.token_kind != "activation":
+ continue
+
+ if token.owner_node_id not in self.prepared_source_mapping:
+ raise ValueError("Activation token has an unknown execution owner")
+ expected_ref = self._expected_execution_ref(token.owner_node_id)
+ owner = self.execution_graph.get_node(token.owner_node_id)
+
+ if token.reference_id != expected_ref.reference_id:
+ raise ValueError("Activation token belongs to another execution reference")
+ if (
+ token.frame.state_id != expected_ref.frame.state_id
+ or token.frame.frame_id != expected_ref.frame.frame_id
+ or token.frame.iteration_path != expected_ref.frame.iteration_path
+ or token.frame.workflow_call_depth != expected_ref.frame.workflow_call_depth
+ ):
+ raise ValueError("Activation token belongs to another execution frame")
+ if token_key != token.token_id:
+ raise ValueError("Activation token mapping key does not match token id")
+ if not isinstance(owner, IfInvocation):
+ activation_fields = getattr(type(owner), "execution_activation_fields", frozenset())
+ if token.port not in activation_fields:
+ raise ValueError(f"Activation token references unknown activation port '{token.port}'")
+ if token.value != token.port:
+ raise ValueError(f"Activation token value '{token.value}' does not match port '{token.port}'")
+ expected_token_id = f"{expected_ref.reference_id}:activation:{token.port}"
+ if token.token_id != expected_token_id:
+ raise ValueError("Activation token has a stale token id")
+
def _rehydrate_resolved_if_exec_branches(self) -> None:
+ self._validate_persisted_activation_tokens()
for exec_node_id, node in self.execution_graph.nodes.items():
if not isinstance(node, IfInvocation):
continue
@@ -5826,6 +5858,9 @@ class GraphExecutionState(BaseModel):
if len(selected_fields) != 1:
raise ValueError(f"If execution node {exec_node_id} has conflicting activation tokens")
selected_field = next(iter(selected_fields))
+ expected_token_id = f"{expected_ref.reference_id}:activation:{selected_field}"
+ if any(token.token_id != expected_token_id for token in activation_tokens):
+ raise ValueError(f"Activation token for If execution node {exec_node_id} has a stale token id")
self._resolve_activation_gate(exec_node_id, selected_field)
self._resolved_if_exec_branches[exec_node_id] = selected_field
continue
@@ -5840,6 +5875,7 @@ class GraphExecutionState(BaseModel):
def _rehydrate_execution_refs(self) -> None:
for exec_node_id in self.prepared_source_mapping:
+ self._get_iteration_path(exec_node_id)
existing = self.execution_refs.get(exec_node_id)
effect_count = existing.effect_count if existing is not None else None
self.execution_refs[exec_node_id] = self._expected_execution_ref(exec_node_id, effect_count=effect_count)
diff --git a/tests/app/services/session_processor/test_if_processor_sqlite.py b/tests/app/services/session_processor/test_if_processor_sqlite.py
new file mode 100644
index 0000000000..5054ee06b2
--- /dev/null
+++ b/tests/app/services/session_processor/test_if_processor_sqlite.py
@@ -0,0 +1,335 @@
+import asyncio
+import uuid
+from contextlib import contextmanager
+from threading import Condition, Event
+from typing import Iterator
+
+import pytest
+from fastapi_events.handlers.local import local_handler
+
+from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.invocations.math import AddInvocation
+from invokeai.app.invocations.primitives import BooleanInvocation
+from invokeai.app.services.events.events_base import EventServiceBase
+from invokeai.app.services.events.events_common import EventBase, QueueItemStatusChangedEvent
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.session_processor.session_processor_default import (
+ DefaultSessionProcessor,
+ DefaultSessionRunner,
+)
+from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue
+from invokeai.app.services.shared.graph import Graph, GraphExecutionState
+from tests.test_nodes import create_edge
+
+
+class _RecordingRegisteredEventService(EventServiceBase):
+ def __init__(self) -> None:
+ self._events: list[EventBase] = []
+ self._events_condition = Condition()
+
+ def dispatch(self, event: EventBase) -> None:
+ with self._events_condition:
+ self._events.append(event)
+ self._events_condition.notify_all()
+ asyncio.run(local_handler.handle((event.__event_name__, event)))
+
+ def wait_for_status(self, item_id: int, status: str, timeout: float = 5) -> bool:
+ def has_status() -> bool:
+ return any(
+ isinstance(event, QueueItemStatusChangedEvent) and event.item_id == item_id and event.status == status
+ for event in self._events
+ )
+
+ with self._events_condition:
+ if has_status():
+ return True
+ return self._events_condition.wait_for(has_status, timeout=timeout)
+
+
+class _Stats:
+ @contextmanager
+ def collect_stats(self, invocation, graph_execution_state_id):
+ yield
+
+ def log_stats(self, graph_execution_state_id) -> None:
+ pass
+
+ def reset_stats(self, graph_execution_state_id) -> None:
+ pass
+
+
+def _build_if_graph(*, condition: bool = True) -> Graph:
+ graph = Graph()
+ graph.add_node(BooleanInvocation(id="condition", value=condition))
+ graph.add_node(AddInvocation(id="true_branch", a=2, b=3))
+ graph.add_node(AddInvocation(id="false_branch", a=10, b=20))
+ graph.add_node(IfInvocation(id="if"))
+ graph.add_node(AddInvocation(id="sink", b=1))
+ graph.add_edge(create_edge("condition", "value", "if", "condition"))
+ 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", "sink", "a"))
+ return graph
+
+
+def _insert_session(queue: SqliteSessionQueue, graph: Graph) -> int:
+ session = GraphExecutionState(graph=graph)
+ with queue._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ INSERT INTO session_queue (
+ queue_id, session, session_id, batch_id, field_values, priority,
+ workflow, origin, destination, retried_from_item_id, user_id
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ "default",
+ session.model_dump_json(warnings=False, exclude_none=True),
+ session.id,
+ str(uuid.uuid4()),
+ None,
+ 0,
+ None,
+ None,
+ None,
+ None,
+ "system",
+ ),
+ )
+ return cursor.lastrowid # type: ignore[return-value]
+
+
+def _source_ids(session: GraphExecutionState, execution_ids: list[str] | set[str]) -> list[str]:
+ return [session.prepared_source_mapping[execution_id] for execution_id in execution_ids]
+
+
+def _assert_if_activation_token(
+ session: GraphExecutionState,
+ *,
+ expected_field: str = "true_input",
+) -> None:
+ activation_tokens = [token for token in session.execution_tokens.values() if token.token_kind == "activation"]
+ assert len(activation_tokens) == 1
+ token = activation_tokens[0]
+ [if_execution_id] = session.source_prepared_mapping["if"]
+ assert token.owner_node_id == if_execution_id
+ assert token.reference_id == session.execution_refs[if_execution_id].reference_id
+ assert token.frame == session.execution_refs[if_execution_id].frame
+ assert token.token_id == f"{token.reference_id}:activation:{expected_field}"
+ assert token.token_id in session.execution_tokens
+ assert token.port == expected_field
+ assert token.value == expected_field
+
+
+def _stop_processor(processor: DefaultSessionProcessor) -> None:
+ processor.stop()
+ for worker in processor._workers:
+ assert worker.thread is not None
+ worker.thread.join(timeout=5)
+ assert not worker.thread.is_alive()
+
+
+def _completed_source_ids(session: GraphExecutionState) -> list[str]:
+ return _source_ids(session, session.results)
+
+
+def registered_event_bus() -> Iterator[_RecordingRegisteredEventService]:
+ yield _RecordingRegisteredEventService()
+
+
+ ("condition", "selected_branch", "unselected_branch", "selected_field"),
+ [
+ (True, "true_branch", "false_branch", "true_input"),
+ (False, "false_branch", "true_branch", "false_input"),
+ ],
+)
+def test_if_cancellation_preserves_activation_and_never_resumes_unselected_branch(
+ mock_invoker: Invoker,
+ registered_event_bus: _RecordingRegisteredEventService,
+ condition: bool,
+ selected_branch: str,
+ unselected_branch: str,
+ selected_field: str,
+) -> None:
+ queue = SqliteSessionQueue(db=mock_invoker.services.board_records._db)
+ mock_invoker.services.events = registered_event_bus
+ mock_invoker.services.session_queue = queue
+ mock_invoker.services.performance_statistics = _Stats()
+ queue.start(mock_invoker)
+
+ processor: DefaultSessionProcessor | None = None
+ item_id = _insert_session(queue, _build_if_graph(condition=condition))
+ completed_sources: list[str] = []
+ session_persisted = Event()
+
+ def cancel_after_if(invocation, queue_item, output) -> None:
+ source_id = queue_item.session.prepared_source_mapping[invocation.id]
+ completed_sources.append(source_id)
+ if source_id == "if":
+ queue.cancel_queue_item(queue_item.item_id)
+
+ processor = DefaultSessionProcessor(
+ session_runner=DefaultSessionRunner(
+ on_after_run_node_callbacks=[cancel_after_if],
+ on_after_run_session_callbacks=[lambda queue_item: session_persisted.set()],
+ ),
+ polling_interval=0,
+ )
+ try:
+ processor.start(mock_invoker)
+ assert registered_event_bus.wait_for_status(item_id, "canceled")
+ assert session_persisted.wait(timeout=5)
+
+ queue_item = queue.get_queue_item(item_id)
+ assert queue_item.status == "canceled"
+ assert queue.get_current("default") is None
+ assert completed_sources == ["condition", selected_branch, "if"]
+ assert _completed_source_ids(queue_item.session) == completed_sources
+ assert unselected_branch not in completed_sources
+ assert "sink" not in completed_sources
+ assert not queue_item.session.is_complete()
+ _assert_if_activation_token(queue_item.session, expected_field=selected_field)
+ finally:
+ _stop_processor(processor)
+
+
+ (
+ "condition",
+ "selected_branch",
+ "unselected_branch",
+ "selected_field",
+ "sink_value",
+ "cancel_after_source",
+ ),
+ [
+ (True, "true_branch", "false_branch", "true_input", 6, "if"),
+ (False, "false_branch", "true_branch", "false_input", 31, "if"),
+ (True, "true_branch", "false_branch", "true_input", 6, "true_branch"),
+ (False, "false_branch", "true_branch", "false_input", 31, "false_branch"),
+ ],
+)
+def test_if_retry_starts_fresh_and_preserves_selected_output_without_stale_activation(
+ mock_invoker: Invoker,
+ registered_event_bus: _RecordingRegisteredEventService,
+ condition: bool,
+ selected_branch: str,
+ unselected_branch: str,
+ selected_field: str,
+ sink_value: int,
+ cancel_after_source: str,
+) -> None:
+ queue = SqliteSessionQueue(db=mock_invoker.services.board_records._db)
+ mock_invoker.services.events = registered_event_bus
+ mock_invoker.services.session_queue = queue
+ mock_invoker.services.performance_statistics = _Stats()
+ queue.start(mock_invoker)
+
+ item_id = _insert_session(queue, _build_if_graph(condition=condition))
+ session_persisted = Event()
+ processor = DefaultSessionProcessor(
+ session_runner=DefaultSessionRunner(
+ on_after_run_node_callbacks=[
+ lambda invocation, queue_item, output: queue.cancel_queue_item(queue_item.item_id)
+ if queue_item.session.prepared_source_mapping[invocation.id] == cancel_after_source
+ else None
+ ],
+ on_after_run_session_callbacks=[lambda queue_item: session_persisted.set()],
+ ),
+ polling_interval=0,
+ )
+ try:
+ processor.start(mock_invoker)
+ assert registered_event_bus.wait_for_status(item_id, "canceled")
+ assert session_persisted.wait(timeout=5)
+ finally:
+ _stop_processor(processor)
+
+ canceled_item = queue.get_queue_item(item_id)
+ _assert_if_activation_token(canceled_item.session, expected_field=selected_field)
+ retry_result = queue.retry_items_by_id("default", [item_id])
+ assert retry_result.retried_item_ids == [item_id]
+
+ retried_item = queue.dequeue()
+ assert retried_item is not None
+ assert retried_item.item_id != item_id
+ assert retried_item.retried_from_item_id == item_id
+ assert retried_item.session.id != canceled_item.session.id
+ assert retried_item.session.results == {}
+ assert retried_item.session.execution_tokens == {}
+ assert retried_item.session.execution_refs == {}
+
+ runner = DefaultSessionRunner()
+ runner.start(services=mock_invoker.services, cancel_event=Event())
+ runner.run(retried_item)
+
+ completed_item = queue.get_queue_item(retried_item.item_id)
+ assert queue.get_queue_item(item_id).status == "canceled"
+ assert completed_item.status == "completed"
+ assert completed_item.session.is_complete()
+ completed_sources = _completed_source_ids(completed_item.session)
+ assert completed_sources == ["condition", selected_branch, "if", "sink"]
+ assert unselected_branch not in completed_sources
+ [sink_execution_id] = completed_item.session.source_prepared_mapping["sink"]
+ assert completed_item.session.results[sink_execution_id].value == sink_value
+ _assert_if_activation_token(completed_item.session, expected_field=selected_field)
+
+
+ ("condition", "selected_branch", "unselected_branch", "selected_field"),
+ [
+ (True, "true_branch", "false_branch", "true_input"),
+ (False, "false_branch", "true_branch", "false_input"),
+ ],
+)
+def test_if_early_cancellation_before_resolution_does_not_run_any_branch_continuation(
+ mock_invoker: Invoker,
+ registered_event_bus: _RecordingRegisteredEventService,
+ condition: bool,
+ selected_branch: str,
+ unselected_branch: str,
+ selected_field: str,
+) -> None:
+ queue = SqliteSessionQueue(db=mock_invoker.services.board_records._db)
+ mock_invoker.services.events = registered_event_bus
+ mock_invoker.services.session_queue = queue
+ mock_invoker.services.performance_statistics = _Stats()
+ queue.start(mock_invoker)
+
+ item_id = _insert_session(queue, _build_if_graph(condition=condition))
+ session_persisted = Event()
+ completed_sources: list[str] = []
+
+ def cancel_after_selected(invocation, queue_item, output) -> None:
+ source_id = queue_item.session.prepared_source_mapping[invocation.id]
+ completed_sources.append(source_id)
+ if source_id == selected_branch:
+ queue.cancel_queue_item(queue_item.item_id)
+
+ processor = DefaultSessionProcessor(
+ session_runner=DefaultSessionRunner(
+ on_after_run_node_callbacks=[cancel_after_selected],
+ on_after_run_session_callbacks=[lambda queue_item: session_persisted.set()],
+ ),
+ polling_interval=0,
+ )
+ try:
+ processor.start(mock_invoker)
+ assert registered_event_bus.wait_for_status(item_id, "canceled")
+ assert session_persisted.wait(timeout=5)
+ finally:
+ _stop_processor(processor)
+
+ canceled_item = queue.get_queue_item(item_id)
+ assert canceled_item.status == "canceled"
+ assert queue.get_current("default") is None
+ assert completed_sources == ["condition", selected_branch]
+ assert _completed_source_ids(canceled_item.session) == completed_sources
+ assert unselected_branch not in completed_sources
+ assert "if" not in completed_sources
+ assert "sink" not in completed_sources
+ assert "if" not in _completed_source_ids(canceled_item.session)
+ _assert_if_activation_token(canceled_item.session, expected_field=selected_field)
+ assert not canceled_item.session.is_complete()
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index 44ebc6a08d..9f1e766ca2 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -6,6 +6,7 @@ from typing import Any
from unittest.mock import Mock
import pytest
+from pydantic import ValidationError
from invokeai.app.invocations.logic import IfInvocation
from invokeai.app.invocations.math import AddInvocation
@@ -42,7 +43,7 @@ def _run(
fail_source_id: str | None = None,
) -> tuple[list[str], GraphExecutionState]:
if force_compatibility_scheduler:
- object.__setattr__(state, "_execution_scheduler", _ExecutionScheduler(state))
+ state._execution_scheduler = _ExecutionScheduler(state)
trace: list[str] = []
while (node := state.next()) is not None:
@@ -57,6 +58,14 @@ def _run(
return trace, state
+def _restore_compatibility_scheduler(state: GraphExecutionState) -> None:
+ state._ready_queues = {}
+ state._ready_node_ids = set()
+ state._active_class = None
+ state._execution_scheduler = _ExecutionScheduler(state)
+ state._rehydrate_ready_queues()
+
+
def _nested_if_graph() -> Graph:
"""Build a mixed graph whose selected outer branch contains an inner If."""
graph = Graph()
@@ -96,7 +105,7 @@ def _run_graph(
) -> tuple[list[str], GraphExecutionState]:
"""Run a constructed graph through either scheduler path."""
if force_compatibility_scheduler:
- object.__setattr__(state, "_execution_scheduler", _ExecutionScheduler(state))
+ state._execution_scheduler = _ExecutionScheduler(state)
trace: list[str] = []
while (node := state.next()) is not None:
@@ -111,6 +120,26 @@ def _run_graph(
return trace, state
+def _run_until_source(
+ state: GraphExecutionState,
+ source_id_to_stop: str,
+ *,
+ force_compatibility_scheduler: bool = False,
+) -> tuple[list[str], GraphExecutionState]:
+ """Run through one source node, modeling a queue cancellation boundary."""
+ if force_compatibility_scheduler:
+ state._execution_scheduler = _ExecutionScheduler(state)
+
+ trace: list[str] = []
+ while (node := state.next()) is not None:
+ source_id = state.prepared_source_mapping[node.id]
+ trace.append(source_id)
+ state.complete(node.id, node.invoke(Mock()))
+ if source_id == source_id_to_stop:
+ break
+ return trace, state
+
+
def _run_both(**kwargs: Any) -> tuple[tuple[list[str], GraphExecutionState], tuple[list[str], GraphExecutionState]]:
base_kwargs = {key: value for key, value in kwargs.items() if key != "force_compatibility_scheduler"}
generic = _run(_load_fixture(), force_compatibility_scheduler=False, **base_kwargs)
@@ -180,6 +209,89 @@ def _activation_projection(state: GraphExecutionState) -> tuple[tuple[str, str,
)
+def _execution_identity_projection(state: GraphExecutionState) -> tuple[Any, ...]:
+ references = tuple(
+ sorted(
+ (
+ state.prepared_source_mapping.get(exec_node_id, exec_node_id),
+ reference.source_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
+ )
+ )
+ tokens = tuple(
+ sorted(
+ (
+ state.prepared_source_mapping.get(token.owner_node_id, token.owner_node_id),
+ token.port,
+ json.dumps(token.value, sort_keys=True),
+ token.token_kind,
+ token.sequence,
+ tuple(token.frame.iteration_path),
+ token.frame.workflow_call_depth,
+ )
+ for token in state.execution_tokens.values()
+ )
+ )
+ effects = tuple(
+ sorted(
+ (
+ state.prepared_source_mapping.get(
+ next(
+ (
+ execution_id
+ for execution_id, reference in state.execution_refs.items()
+ if reference.reference_id == reference_id
+ ),
+ reference_id,
+ ),
+ reference_id,
+ ),
+ json.dumps(
+ [
+ effect.model_dump(mode="json", warnings=False) if hasattr(effect, "model_dump") else effect
+ for effect in effect_values
+ ],
+ sort_keys=True,
+ ),
+ )
+ for reference_id, effect_values in state.execution_effects.items()
+ )
+ )
+ return references, tokens, effects
+
+
+def _assert_execution_identity_consistent(state: GraphExecutionState) -> None:
+ for exec_node_id, reference in state.execution_refs.items():
+ if exec_node_id not in state.prepared_source_mapping:
+ continue
+ expected = state._expected_execution_ref(exec_node_id, effect_count=reference.effect_count)
+ assert reference.reference_id == expected.reference_id
+ assert reference.state_id == expected.state_id
+ assert reference.exec_node_id == expected.exec_node_id
+ assert reference.source_node_id == expected.source_node_id
+ assert reference.frame == expected.frame
+ for token_key, token in state.execution_tokens.items():
+ expected = state.execution_refs.get(token.owner_node_id) or state._expected_execution_ref(token.owner_node_id)
+ assert token_key == token.token_id
+ assert token.reference_id == expected.reference_id
+ assert token.owner_node_id == expected.exec_node_id
+ assert token.frame.state_id == expected.frame.state_id
+ assert token.frame.frame_id == expected.frame.frame_id
+ assert token.frame.iteration_path == expected.frame.iteration_path
+ assert token.frame.workflow_call_depth == expected.frame.workflow_call_depth
+ if token.token_kind == "activation":
+ owner = state.execution_graph.nodes[token.owner_node_id]
+ activation_fields = getattr(type(owner), "execution_activation_fields", frozenset())
+ assert token.port in activation_fields
+ assert token.token_id == f"{expected.reference_id}:activation:{token.port}"
+ assert token.value == token.port
+
+
def test_static_dag_fresh_execution_has_matching_source_trace() -> None:
generic, compatibility = _run_both()
@@ -282,7 +394,7 @@ def test_nested_if_checkpoint_restore_matches_compatibility_scheduler() -> None:
)
restored = load_execution_state(dump_execution_state(checkpoint_state))
if force_compatibility_scheduler:
- object.__setattr__(restored, "_execution_scheduler", _ExecutionScheduler(restored))
+ _restore_compatibility_scheduler(restored)
remaining_trace, restored_state = _run_graph(
restored,
force_compatibility_scheduler=force_compatibility_scheduler,
@@ -324,7 +436,7 @@ def test_nested_if_failure_round_trip_matches_compatibility_scheduler() -> None:
restored_generic = load_execution_state(dump_execution_state(generic_state))
restored_compatibility = load_execution_state(dump_execution_state(compatibility_state))
- object.__setattr__(restored_compatibility, "_execution_scheduler", _ExecutionScheduler(restored_compatibility))
+ _restore_compatibility_scheduler(restored_compatibility)
assert restored_generic.next() is None
assert restored_compatibility.next() is None
assert _state_projection(restored_generic) == _state_projection(restored_compatibility)
@@ -384,7 +496,7 @@ def test_injected_failure_round_trip_preserves_both_scheduler_terminal_state() -
generic, compatibility = _run_both(fail_source_id="right")
restored_generic = load_execution_state(dump_execution_state(generic[1]))
restored_compatibility = load_execution_state(dump_execution_state(compatibility[1]))
- object.__setattr__(restored_compatibility, "_execution_scheduler", _ExecutionScheduler(restored_compatibility))
+ _restore_compatibility_scheduler(restored_compatibility)
assert restored_generic.next() is None
assert restored_compatibility.next() is None
@@ -408,12 +520,12 @@ def test_durable_snapshot_corpus_round_trips_without_losing_terminal_state(fixtu
for force_compatibility_scheduler in (False, True):
candidate = load_execution_state(dump_execution_state(state))
if force_compatibility_scheduler:
- object.__setattr__(candidate, "_execution_scheduler", _ExecutionScheduler(candidate))
+ _restore_compatibility_scheduler(candidate)
assert candidate.next() is None
assert candidate.is_complete()
generic = load_execution_state(dump_execution_state(state))
compatibility = load_execution_state(dump_execution_state(state))
- object.__setattr__(compatibility, "_execution_scheduler", _ExecutionScheduler(compatibility))
+ _restore_compatibility_scheduler(compatibility)
assert _state_projection(generic) == _state_projection(compatibility)
else:
generic_trace, generic_state = _run(restored)
@@ -466,3 +578,220 @@ def test_generic_legacy_shaped_if_does_not_prune_or_skip_during_resolution(
assert state.results[sink_id].value == 7
assert state.is_complete()
assert deleted_edges == []
+
+
[email protected]("stop_after_source", ["outer_if", "inner_false"])
+def test_if_partial_state_round_trip_rebuilds_fresh_runtime_and_matches_both_scheduler_paths(
+ stop_after_source: str,
+) -> None:
+ """A partial If state round-trips and a fresh runtime matches both scheduler paths."""
+ partial_projections: list[tuple[Any, ...]] = []
+ projections: list[tuple[list[str], GraphExecutionState]] = []
+
+ for force_compatibility_scheduler in (False, True):
+ partial_trace, canceled_state = _run_until_source(
+ GraphExecutionState(graph=_nested_if_graph()),
+ stop_after_source,
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ )
+ expected_partial_trace = ["outer_condition", "inner_condition"]
+ if stop_after_source == "inner_false":
+ expected_partial_trace.append("inner_false")
+ else:
+ expected_partial_trace.extend(["inner_false", "inner_if", "outer_if"])
+ assert partial_trace == expected_partial_trace
+ assert "inner_true" not in {
+ canceled_state.prepared_source_mapping[execution_id] for execution_id in canceled_state.results
+ }
+ assert "outer_false" not in {
+ canceled_state.prepared_source_mapping[execution_id] for execution_id in canceled_state.results
+ }
+ assert not canceled_state.is_complete()
+ assert _activation_projection(canceled_state) == (
+ ("inner_if", "false_input", "false_input", ()),
+ ("outer_if", "true_input", "true_input", ()),
+ )
+ partial_snapshot = dump_execution_state(canceled_state)
+ restored_canceled = load_execution_state(partial_snapshot)
+ restored_expected = load_execution_state(partial_snapshot)
+ if force_compatibility_scheduler:
+ _restore_compatibility_scheduler(restored_canceled)
+ assert _state_projection(restored_canceled) == _state_projection(canceled_state)
+ assert _activation_projection(restored_canceled) == _activation_projection(canceled_state)
+ assert dump_execution_state(restored_canceled)["execution_tokens"] == partial_snapshot["execution_tokens"]
+ assert dump_execution_state(restored_canceled)["execution_effects"] == partial_snapshot["execution_effects"]
+ assert _execution_identity_projection(restored_canceled) == _execution_identity_projection(restored_expected)
+ _assert_execution_identity_consistent(restored_canceled)
+ partial_projections.append(
+ (_state_projection(restored_canceled), _execution_identity_projection(restored_canceled))
+ )
+
+ retried_state = GraphExecutionState(graph=canceled_state.graph.model_copy(deep=True))
+ assert retried_state.id != canceled_state.id
+ assert retried_state.results == {}
+ assert retried_state.execution_refs == {}
+ assert retried_state.execution_tokens == {}
+
+ retried_trace, retried_state = _run_graph(
+ retried_state,
+ force_compatibility_scheduler=force_compatibility_scheduler,
+ )
+ projections.append((retried_trace, retried_state))
+
+ assert partial_projections[0] == partial_projections[1]
+ assert (
+ projections[0][0]
+ == projections[1][0]
+ == [
+ "outer_condition",
+ "inner_condition",
+ "inner_false",
+ "inner_if",
+ "outer_if",
+ "sink",
+ ]
+ )
+ assert _state_projection(projections[0][1]) == _state_projection(projections[1][1])
+ assert _activation_projection(projections[0][1]) == _activation_projection(projections[1][1])
+ assert _execution_identity_projection(projections[0][1]) == _execution_identity_projection(projections[1][1])
+ _assert_execution_identity_consistent(projections[0][1])
+ _assert_execution_identity_consistent(projections[1][1])
+ assert projections[0][1].results[next(iter(projections[0][1].source_prepared_mapping["sink"]))].value == 7
+
+
+ "tampered_field",
+ [
+ "token_id",
+ "owner_node_id",
+ "reference_id",
+ "frame_id",
+ "state_id",
+ "iteration_path",
+ "workflow_call_depth",
+ "blank_owner_node_id",
+ "blank_frame_id",
+ "blank_state_id",
+ "mapping_key",
+ "both_ids",
+ ],
+)
+def test_rehydrated_if_rejects_tampered_activation_identity(tampered_field: str) -> None:
+ """A persisted activation token with stale identity or frame data is rejected."""
+ _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")
+ snapshot = dump_execution_state(partial_state)
+ token_id, token = next(
+ (token_id, token)
+ for token_id, token in snapshot["execution_tokens"].items()
+ if token["token_kind"] == "activation"
+ )
+ source_if_id = partial_state.prepared_source_mapping[token["owner_node_id"]]
+
+ valid_restored = load_execution_state(snapshot)
+ valid_plan = valid_restored._scheduler()._scheduler.plan
+ dependency = next(
+ dependency
+ for plan_node in valid_plan.nodes.values()
+ for dependency in plan_node.activation_dependencies
+ if dependency.owner_id == source_if_id
+ )
+ assert valid_restored._is_activation_dependency_satisfied(dependency)
+ restored_token = valid_restored.execution_tokens[token_id]
+ expected_ref = valid_restored.execution_refs[restored_token.owner_node_id]
+ assert restored_token.token_id == token_id == f"{expected_ref.reference_id}:activation:{restored_token.port}"
+ assert restored_token.reference_id == expected_ref.reference_id
+ assert restored_token.owner_node_id == expected_ref.exec_node_id
+ assert restored_token.frame == expected_ref.frame
+
+ stale_snapshot = json.loads(json.dumps(snapshot))
+ stale_token = stale_snapshot["execution_tokens"][token_id]
+ if tampered_field == "token_id":
+ stale_token["token_id"] = "stale-token"
+ elif tampered_field == "owner_node_id":
+ stale_token["owner_node_id"] = "stale-owner"
+ elif tampered_field == "reference_id":
+ stale_token["reference_id"] = "stale-reference"
+ elif tampered_field == "frame_id":
+ stale_token["frame"]["frame_id"] = "stale-frame"
+ elif tampered_field == "state_id":
+ stale_token["frame"]["state_id"] = "stale-state"
+ elif tampered_field == "iteration_path":
+ stale_token["frame"]["iteration_path"] = [1]
+ elif tampered_field == "workflow_call_depth":
+ stale_token["frame"]["workflow_call_depth"] = 1
+ elif tampered_field == "blank_owner_node_id":
+ stale_token["owner_node_id"] = ""
+ elif tampered_field == "blank_frame_id":
+ stale_token["frame"]["frame_id"] = ""
+ elif tampered_field == "blank_state_id":
+ stale_token["frame"]["state_id"] = ""
+ elif tampered_field == "mapping_key":
+ stale_snapshot["execution_tokens"]["stale-key"] = stale_snapshot["execution_tokens"].pop(token_id)
+ else:
+ stale_snapshot["execution_tokens"]["stale-key"] = stale_snapshot["execution_tokens"].pop(token_id)
+ stale_snapshot["execution_tokens"]["stale-key"]["token_id"] = "stale-key"
+ with pytest.raises(ValidationError, match="Activation token|Execution token"):
+ load_execution_state(stale_snapshot)
+
+
+def test_rehydrated_if_rejects_activation_token_with_ghost_owner_and_reference() -> None:
+ _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")
+ snapshot = dump_execution_state(partial_state)
+ token_id, token = next(
+ (token_id, token)
+ for token_id, token in snapshot["execution_tokens"].items()
+ if token["token_kind"] == "activation"
+ )
+ expected_ref = partial_state._expected_execution_ref(token["owner_node_id"]).model_dump(mode="json")
+ ghost_ref = {**expected_ref, "exec_node_id": "ghost", "reference_id": f"{snapshot['id']}:ghost"}
+ snapshot["execution_refs"]["ghost"] = ghost_ref
+ ghost_token_id = f"{ghost_ref['reference_id']}:activation:{token['port']}"
+ ghost_token = {
+ **token,
+ "token_id": ghost_token_id,
+ "reference_id": ghost_ref["reference_id"],
+ "owner_node_id": "ghost",
+ }
+ snapshot["execution_tokens"].pop(token_id)
+ snapshot["execution_tokens"][ghost_token_id] = ghost_token
+
+ with pytest.raises(ValidationError, match="Activation token|Execution token"):
+ load_execution_state(snapshot)
+
+
+def test_rehydrated_if_rejects_activation_token_on_invocation_without_declared_field() -> None:
+ _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")
+ snapshot = dump_execution_state(partial_state)
+ ordinary_exec_id = next(
+ execution_id
+ for execution_id, source_id in partial_state.prepared_source_mapping.items()
+ if source_id == "inner_false"
+ )
+ reference = partial_state._expected_execution_ref(ordinary_exec_id).model_dump(mode="json")
+ token_id = f"{reference['reference_id']}:activation:value"
+ snapshot["execution_tokens"][token_id] = {
+ "token_id": token_id,
+ "reference_id": reference["reference_id"],
+ "owner_node_id": ordinary_exec_id,
+ "port": "value",
+ "frame": reference["frame"],
+ "value": "value",
+ "token_kind": "activation",
+ }
+
+ with pytest.raises(ValidationError, match="Activation token|Execution token"):
+ load_execution_state(snapshot)
+
+
+def test_rehydrated_activation_token_allows_unknown_frame_metadata() -> None:
+ _, partial_state = _run_until_source(GraphExecutionState(graph=_nested_if_graph()), "outer_if")
+ snapshot = dump_execution_state(partial_state)
+ 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]["frame"]["future_frame_metadata"] = "preserved"
+
+ restored = load_execution_state(snapshot)
+ assert restored.execution_tokens[token_id].frame.model_extra["future_frame_metadata"] == "preserved"
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index 2b6d6f4bc3..7767114319 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -3685,6 +3685,54 @@ def test_graph_state_round_trip_rebuilds_iteration_paths_for_legacy_session():
assert execute_all_nodes(resumed)
+def test_graph_state_rehydrates_legacy_for_if_snapshot_without_iteration_paths():
+ graph = Graph()
+ graph.add_node(ForInvocation(id="for", collection=[True, False]))
+ graph.add_node(IfInvocation(id="if", true_input="true branch", false_input="false branch"))
+ graph.add_node(ForReturnInvocation(id="return"))
+ graph.add_node(AnyTypeTestInvocation(id="after"))
+ graph.add_edge(create_edge("for", "item", "if", "condition"))
+ graph.add_edge(create_edge("if", "value", "return", "output"))
+ graph.add_edge(create_edge("for", "output_collection", "after", "value"))
+
+ state = GraphExecutionState(graph=add_test_loop_linkages(graph))
+ for _ in range(2):
+ invocation, output = invoke_next(state)
+ assert invocation is not None
+ assert output is not None
+
+ if_exec_id = next(iter(state.source_prepared_mapping["if"]))
+ activation_token = next(
+ token
+ for token in state.execution_tokens.values()
+ if token.owner_node_id == if_exec_id and token.token_kind == "activation"
+ )
+
+ legacy_payload = state.model_dump(mode="json", warnings=False, exclude_none=True)
+ legacy_payload.pop("prepared_iteration_paths")
+
+ restored = load_execution_state(legacy_payload)
+
+ restored_if_exec_id = next(iter(restored.source_prepared_mapping["if"]))
+ restored_activation_token = next(
+ token
+ for token in restored.execution_tokens.values()
+ if token.owner_node_id == restored_if_exec_id and token.token_kind == "activation"
+ )
+ assert restored_if_exec_id == if_exec_id
+ assert restored._get_iteration_path(restored_if_exec_id) == (0,)
+ assert restored_activation_token.port == "true_input"
+ assert restored_activation_token.frame == restored.get_execution_ref(restored_if_exec_id).frame
+ assert restored_activation_token.frame == activation_token.frame
+ assert restored._activation_gate(restored_if_exec_id).selected_branch == "true_input"
+
+ execute_all_nodes(restored)
+
+ after_exec_id = next(iter(restored.source_prepared_mapping["after"]))
+ assert restored.results[after_exec_id].value == ["true branch", "false branch"]
+ assert restored.is_complete()
+
+
def test_if_graph_state_resumes_resolved_branch_after_json_round_trip():
graph = Graph()
graph.add_node(BooleanInvocation(id="condition", value=True))