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): migrate and quarantine runtime snapshots

JPPhoto5c19a60e0d23
diff --git a/invokeai/app/services/session_processor/workflow_call_batch.py b/invokeai/app/services/session_processor/workflow_call_batch.py
index 01deee5d7a..fe492fbb32 100644
--- a/invokeai/app/services/session_processor/workflow_call_batch.py
+++ b/invokeai/app/services/session_processor/workflow_call_batch.py
@@ -20,6 +20,7 @@ from invokeai.app.services.session_queue.session_queue_common import (
calc_session_count,
create_session_nfv_tuples,
)
+from invokeai.app.services.shared.execution_state_migration import load_execution_state
from invokeai.app.services.shared.graph import GraphExecutionState, WorkflowCallFrame
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.shared.workflow_graph_builder import (
@@ -635,7 +636,7 @@ def build_batch_child_workflow_session_results(
child_session_results: list[WorkflowCallChildSessionResult] = []
for session_id, session_json, field_values_json in create_session_nfv_tuples(batch, maximum_children):
- generated_session = GraphExecutionState.model_validate_json(session_json)
+ generated_session = load_execution_state(json.loads(session_json))
child_session = parent_session.create_child_workflow_execution_state(generated_session.graph, call_frame)
child_session.id = session_id
field_values = [NodeFieldValue.model_validate(field_value) for field_value in json.loads(field_values_json)]
diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.py
index 451cbff533..b30d35c038 100644
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@ -44,8 +44,11 @@ from invokeai.app.services.session_queue.session_queue_common import (
prepare_values_to_insert,
uuid_string,
)
-from invokeai.app.services.shared.execution_state_migration import dump_execution_state
-from invokeai.app.services.shared.graph import GraphExecutionState
+from invokeai.app.services.shared.execution_state_migration import (
+ UnsupportedExecutionStateVersionError,
+ dump_execution_state,
+)
+from invokeai.app.services.shared.graph import Graph, GraphExecutionState
from invokeai.app.services.shared.pagination import CursorPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
@@ -578,20 +581,48 @@ class SqliteSessionQueue(SessionQueueBase):
# if the item was concurrently moved to a terminal state (e.g. canceled), so we only need
# to guard against two dequeues racing for the same pending row.
with self._dequeue_lock:
- with self._db.transaction() as cursor:
- cursor.execute(query)
- result = cast(Union[sqlite3.Row, None], cursor.fetchone())
- if result is None:
- return None
- queue_item = SessionQueueItem.queue_item_from_dict(dict(result))
- queue_item = self._apply_device_affinity(queue_item, resident_model_keys)
- # Record the claiming worker's device so the UI can label the item by GPU. Passing the
- # item we already materialized lets _set_queue_item_status patch it in place instead of
- # re-reading (and re-parsing the session graph of) the row we just read.
- queue_item = self._set_queue_item_status(
- item_id=queue_item.item_id, status="in_progress", device=device, queue_item=queue_item
- )
- return queue_item
+ while True:
+ with self._db.transaction() as cursor:
+ cursor.execute(query)
+ result = cast(Union[sqlite3.Row, None], cursor.fetchone())
+ if result is None:
+ return None
+ raw_result = dict(result)
+ try:
+ queue_item = SessionQueueItem.queue_item_from_dict(raw_result)
+ except UnsupportedExecutionStateVersionError as exc:
+ self._quarantine_unreadable_queue_item(raw_result, exc)
+ continue
+ queue_item = self._apply_device_affinity(queue_item, resident_model_keys)
+ # Record the claiming worker's device so the UI can label the item by GPU. Passing the
+ # item we already materialized lets _set_queue_item_status patch it in place instead of
+ # re-reading (and re-parsing the session graph of) the row we just read.
+ queue_item = self._set_queue_item_status(
+ item_id=queue_item.item_id, status="in_progress", device=device, queue_item=queue_item
+ )
+ return queue_item
+
+ def _quarantine_unreadable_queue_item(self, raw_queue_item: dict[str, Any], error: Exception) -> None:
+ """Fail a pending row whose runtime snapshot is newer than this worker can read.
+
+ The real session cannot be hydrated, so use a minimal in-memory placeholder only for the
+ status transition/event. The persisted session remains untouched for postmortem recovery.
+ """
+
+ placeholder = SessionQueueItem.model_construct(**raw_queue_item)
+ placeholder.status = "pending"
+ placeholder.session = GraphExecutionState(graph=Graph())
+ placeholder.workflow = None
+ placeholder.field_values = None
+ message = f"Unable to load execution state: {error}"
+ self._set_queue_item_status(
+ item_id=placeholder.item_id,
+ status="failed",
+ error_type=type(error).__name__,
+ error_message=message,
+ error_traceback=message,
+ queue_item=placeholder,
+ )
def _apply_device_affinity(self, candidate: SessionQueueItem, resident_keys: set[str]) -> SessionQueueItem:
"""Swap the fairness-chosen candidate for a nearby same-user, same-priority pending item
diff --git a/invokeai/app/services/shared/execution_state_migration.py b/invokeai/app/services/shared/execution_state_migration.py
index 1cce42640d..1924171ede 100644
--- a/invokeai/app/services/shared/execution_state_migration.py
+++ b/invokeai/app/services/shared/execution_state_migration.py
@@ -1,11 +1,12 @@
"""Compatibility helpers for persisted internal execution-state snapshots."""
-from collections.abc import Mapping
+from collections.abc import Callable, Mapping
from typing import Any, Final
from invokeai.app.services.shared.graph import GraphExecutionState
CURRENT_EXECUTION_STATE_VERSION: Final[int] = 1
+LEGACY_EXECUTION_STATE_VERSION: Final[int] = 0
class UnsupportedExecutionStateVersionError(ValueError):
@@ -25,15 +26,35 @@ def dump_execution_state(state: GraphExecutionState) -> dict[str, Any]:
return snapshot
+def _migrate_legacy_snapshot(payload: Mapping[str, Any]) -> dict[str, Any]:
+ """Convert the original unmarked raw snapshot into the current payload shape."""
+
+ return dict(payload)
+
+
+def _migrate_v1_snapshot(payload: Mapping[str, Any]) -> dict[str, Any]:
+ """Validate the v1 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
+# 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,
+}
+
+
def load_execution_state(snapshot: Mapping[str, Any]) -> GraphExecutionState:
"""Load a versioned snapshot or a legacy unwrapped execution state."""
if not isinstance(snapshot, Mapping):
raise TypeError("Execution state snapshot must be a mapping")
if "version" not in snapshot and "execution_state_version" not in snapshot:
- return GraphExecutionState.model_validate(snapshot, strict=False)
-
- if "version" in snapshot:
+ version = LEGACY_EXECUTION_STATE_VERSION
+ payload = snapshot
+ elif "version" in snapshot:
version = snapshot["version"]
payload = snapshot.get("state")
if not isinstance(payload, Mapping):
@@ -50,10 +71,21 @@ def load_execution_state(snapshot: Mapping[str, Any]) -> GraphExecutionState:
f"Execution state snapshot version {version} is newer than supported version "
f"{CURRENT_EXECUTION_STATE_VERSION}"
)
- if version != CURRENT_EXECUTION_STATE_VERSION:
+ migrated_payload = payload
+ while version < CURRENT_EXECUTION_STATE_VERSION:
+ migrate = _SNAPSHOT_MIGRATIONS.get(version)
+ if migrate is None:
+ raise UnsupportedExecutionStateVersionError(
+ f"Execution state snapshot version {version} has no migration to "
+ f"{CURRENT_EXECUTION_STATE_VERSION}"
+ )
+ migrated_payload = migrate(migrated_payload)
+ version += 1
+
+ migrate = _SNAPSHOT_MIGRATIONS.get(version)
+ if migrate is None:
raise UnsupportedExecutionStateVersionError(
f"Execution state snapshot version {version} is unsupported; current version is "
f"{CURRENT_EXECUTION_STATE_VERSION}"
)
-
- return GraphExecutionState.model_validate(payload, strict=False)
+ return GraphExecutionState.model_validate(migrate(migrated_payload), strict=False)
diff --git a/tests/app/services/session_queue/test_session_queue_dequeue.py b/tests/app/services/session_queue/test_session_queue_dequeue.py
index a185fcbc1b..c07d97f052 100644
--- a/tests/app/services/session_queue/test_session_queue_dequeue.py
+++ b/tests/app/services/session_queue/test_session_queue_dequeue.py
@@ -14,6 +14,7 @@ from invokeai.app.services.session_queue.session_queue_sqlite import (
ROUND_ROBIN_DEQUEUE_QUERY,
SqliteSessionQueue,
)
+from invokeai.app.services.shared.execution_state_migration import CURRENT_EXECUTION_STATE_VERSION
from invokeai.app.services.shared.graph import Graph, GraphExecutionState
_EMPTY_SESSION_JSON = json.dumps(to_jsonable_python(GraphExecutionState(graph=Graph()).model_dump()))
@@ -126,6 +127,34 @@ def test_fifo_returns_none_when_empty(session_queue_fifo: SqliteSessionQueue) ->
assert session_queue_fifo.dequeue() is None
+def test_fifo_quarantines_future_snapshot_and_dequeues_later_work(
+ session_queue_fifo: SqliteSessionQueue,
+) -> None:
+ future_session = json.loads(_EMPTY_SESSION_JSON)
+ future_session["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSION + 1
+ future_item_id = _insert_queue_item(
+ session_queue_fifo,
+ "default",
+ "future-user",
+ session_json=json.dumps(future_session),
+ )
+ valid_item_id = _insert_queue_item(session_queue_fifo, "default", "valid-user")
+
+ dequeued = session_queue_fifo.dequeue()
+
+ assert dequeued is not None
+ assert dequeued.item_id == valid_item_id
+ with session_queue_fifo._db.transaction() as cursor:
+ cursor.execute(
+ "SELECT status, error_type, error_message FROM session_queue WHERE item_id = ?",
+ (future_item_id,),
+ )
+ status, error_type, error_message = cursor.fetchone()
+ assert status == "failed"
+ assert error_type == "UnsupportedExecutionStateVersionError"
+ assert "newer than supported" in error_message
+
+
# ---------------------------------------------------------------------------
# Round-robin tests
# ---------------------------------------------------------------------------
diff --git a/tests/app/services/shared/test_execution_state_migration.py b/tests/app/services/shared/test_execution_state_migration.py
index e60011916a..750d77db80 100644
--- a/tests/app/services/shared/test_execution_state_migration.py
+++ b/tests/app/services/shared/test_execution_state_migration.py
@@ -62,6 +62,15 @@ def test_loads_temporary_versioned_envelope() -> None:
assert restored.id == state.id
+def test_migrates_explicit_legacy_version() -> None:
+ state = _make_state()
+ raw = state.model_dump(mode="json", warnings=False, exclude_none=True)
+
+ restored = load_execution_state({"version": 0, "state": raw})
+
+ assert restored.model_dump(mode="json", warnings=False, exclude_none=True) == raw
+
+
def test_rejects_future_execution_state_versions() -> None:
snapshot = dump_execution_state(_make_state())
snapshot["execution_state_version"] = CURRENT_EXECUTION_STATE_VERSION + 1