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.

Merge remote-tracking branch 'origin/main' into workflow-follow-ups

JPPhotob5fdb57f4bfc
diff --cc invokeai/app/services/session_queue/session_queue_base.py
index b3b91a5d4a,8b24f4782b..c35bf8b9c2
--- a/invokeai/app/services/session_queue/session_queue_base.py
+++ b/invokeai/app/services/session_queue/session_queue_base.py
@@@ -255,11 -279,10 +279,15 @@@ class SessionQueueBase(ABC)
"""Gets a session queue item by ID for a given queue"""
pass
+ def get_queue_item_for_api(self, item_id: int) -> SessionQueueItem:
+ """Gets a queue item in the response projection used by API reads."""
+ return self.get_queue_item(item_id=item_id)
+
+ @abstractmethod
+ def get_queue_item_workflow_json(self, item_id: int) -> str | None:
+ """Gets only the workflow metadata JSON for a queue item, if present."""
+ pass
+
@abstractmethod
def set_queue_item_session(self, item_id: int, session: GraphExecutionState) -> SessionQueueItem:
"""Sets the session for a session queue item. Use this to update the session state."""
diff --cc invokeai/app/services/session_queue/session_queue_sqlite.py
index 026ac2b9af,c49a1f1183..393059c316
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@@ -1415,21 -1575,14 +1575,27 @@@ class SqliteSessionQueue(SessionQueueBa
result = cast(Union[sqlite3.Row, None], cursor.fetchone())
if result is None:
raise SessionQueueItemNotFoundError(f"No queue item with id {item_id}")
- return SessionQueueItem.queue_item_from_dict(dict(result))
+ return self._hydrate_queue_item(dict(result), quarantine=False)
+
+ def get_queue_item(self, item_id: int) -> SessionQueueItem:
+ return self._get_queue_item_with_load_status(item_id)[0]
+
+ def get_queue_item_for_api(self, item_id: int) -> SessionQueueItem:
+ return self._get_queue_item_for_api(item_id)
+ def get_queue_item_workflow_json(self, item_id: int) -> str | None:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT workflow
+ FROM session_queue
+ WHERE item_id = ?
+ """,
+ (item_id,),
+ )
+ result = cast(Union[sqlite3.Row, None], cursor.fetchone())
+ return cast(str | None, result["workflow"]) if result is not None else None
+
def save_queue_item_session(self, item_id: int, session: GraphExecutionState) -> None:
with self._db.transaction() as cursor:
# Use exclude_none so we don't end up with a bunch of nulls in the graph - this can cause validation errors
diff --cc invokeai/app/services/shared/invocation_context.py
index 713e0b6648,856c5b4f52..fd83d8461b
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@@ -66,9 -68,20 +68,23 @@@ class InvocationContextData
"""The invocation that is being executed."""
source_invocation_id: str
"""The ID of the invocation from which the currently executing invocation was prepared."""
+ workflow_json: str | None = None
+ """Cached workflow JSON used by repeated image/video saves in this invocation context."""
+ workflow_json_loaded: bool = False
+ execution_frame: tuple[int, ...] = ()
+ """The active prepared execution node's loop iteration path."""
+ execution_state_id: str | None = None
+ """The owning graph execution-state identity for effect ownership validation."""
+ execution_frame_id: str | None = None
+ """The durable frame identity for effect ownership validation."""
+ execution_workflow_call_depth: int = 0
+ """The active workflow-call depth for effect ownership validation."""
+ execution_child_capability: "ChildExecutionCapability | None" = None
+ """Engine-issued authority for lifecycle effects in this invocation frame."""
+ execution_workflow_authorizer: Callable[[str], Any] | None = None
+ """Engine-owned saved-workflow authorization callback, when enabled."""
+ execution_workflow_inputs: dict[str, Any] | None = None
+ """Resolved saved-workflow inputs supplied by the execution adapter."""
class InvocationContextInterface:
@@@ -76,19 -89,19 +92,31 @@@
self._services = services
self._data = data
+ def _get_workflow_json(self) -> str | None:
+ if not self._data.workflow_json_loaded:
+ queue_item = self._data.queue_item
+ if queue_item.workflow is not None:
+ self._data.workflow_json = queue_item.workflow.model_dump_json()
+ elif queue_item.root_item_id is not None:
+ self._data.workflow_json = self._services.session_queue.get_queue_item_workflow_json(
+ queue_item.root_item_id
+ )
+ self._data.workflow_json_loaded = True
+ return self._data.workflow_json
+
+ def _build_execution_effects(data: InvocationContextData) -> ExecutionEffectsRecorder:
+ return ExecutionEffectsRecorder(
+ source_node_id=getattr(data.invocation, "id", None) or data.source_invocation_id or "context",
+ frame_path=data.execution_frame,
+ state_id=data.execution_state_id,
+ frame_id=data.execution_frame_id,
+ workflow_call_depth=data.execution_workflow_call_depth,
+ allow_lifecycle_effects=data.execution_child_capability is not None,
+ child_capability=data.execution_child_capability,
+ )
+
+
class BoardsInterface(InvocationContextInterface):
def create(self, board_name: str) -> BoardDTO:
"""Creates a board for the current user.
diff --cc tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
index 2a9e351991,6a9f51ad95..ea85a8b929
--- a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
+++ b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
@@@ -1,21 -1,15 +1,24 @@@
"""Tests for workflow-call relationship metadata on session_queue items."""
import uuid
+from pathlib import Path
+ from threading import Barrier, Event, Thread
+ from types import SimpleNamespace
+from unittest.mock import MagicMock
import pytest
+from PIL import Image
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
-from invokeai.app.services.events.events_common import QueueItemsRetriedEvent, QueueItemStatusChangedEvent
+from invokeai.app.services.events.events_common import (
+ InvocationStartedEvent,
+ QueueItemsRetriedEvent,
+ QueueItemStatusChangedEvent,
+)
+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.names.names_default import SimpleNameService
+ from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner
from invokeai.app.services.session_queue.session_queue_common import (
NodeFieldValue,
SessionQueueItemNotFoundError,
@@@ -106,23 -96,22 +109,39 @@@ def _insert_queue_item
return cursor.lastrowid
+def _workflow_without_id() -> WorkflowWithoutID:
+ return WorkflowWithoutID(
+ name="Parent workflow",
+ author="Tester",
+ description="",
+ version="1.0.0",
+ contact="",
+ tags="",
+ notes="",
+ exposedFields=[],
+ meta=WorkflowMeta(version="1.0.0", category="user"),
+ nodes=[],
+ edges=[],
+ form=None,
+ )
+
+
+ def _build_waiting_workflow_call_parent(
+ session_queue: SqliteSessionQueue, child_count: int
+ ) -> tuple[int, GraphExecutionState, list[GraphExecutionState]]:
+ graph = Graph()
+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))
+ parent_session = GraphExecutionState(graph=graph)
+ invocation = parent_session.next()
+ assert isinstance(invocation, CallSavedWorkflowInvocation)
+ frame = parent_session.build_workflow_call_frame(invocation.id, invocation.workflow_id)
+ parent_session.begin_waiting_on_workflow_call(frame)
+ child_sessions = [parent_session.create_child_workflow_execution_state(Graph(), frame) for _ in range(child_count)]
+ parent_session.attach_waiting_workflow_call_child_sessions(child_sessions)
+ parent_item_id = _insert_queue_item(session_queue, session=parent_session, status="in_progress")
+ return parent_item_id, parent_session, child_sessions
+
+
def test_get_queue_item_round_trips_workflow_call_metadata(session_queue: SqliteSessionQueue) -> None:
session = GraphExecutionState(graph=Graph())
session_json = session.model_dump_json(warnings=False)
@@@ -281,33 -323,139 +355,164 @@@ def test_enqueue_workflow_call_child_in
assert child_queue_item.root_item_id == parent_item_id
assert child_queue_item.workflow_call_depth == 1
assert child_queue_item.session_id == child_session.id
+ assert child_queue_item.workflow is None
+
+ image_files = DiskImageFileStorage(tmp_path / "images")
+ mock_invoker.services.session_queue = session_queue
+ mock_invoker.services.image_files = image_files
+ mock_invoker.services.names = SimpleNameService()
+ mock_invoker.services.urls = LocalUrlService()
+ image_files.start(mock_invoker)
+ mock_invoker.services.images.start(mock_invoker)
+
+ images = ImagesInterface(
+ mock_invoker.services,
+ InvocationContextData(
+ queue_item=child_queue_item,
+ invocation=MagicMock(is_intermediate=False, id="image-node"),
+ source_invocation_id="image-node",
+ ),
+ MagicMock(),
+ )
+ dto = images.save(Image.new("RGB", (4, 4)))
+
+ workflow_json = _workflow_without_id().model_dump_json()
+ with Image.open(image_files.get_path(dto.image_name)) as saved:
+ assert saved.info["invokeai_workflow"] == workflow_json
+ assert mock_invoker.services.images.get_workflow(dto.image_name) == workflow_json
+ def test_enqueue_workflow_call_child_rejects_canceled_stale_parent(
+ session_queue: SqliteSessionQueue,
+ ) -> None:
+ parent_graph = Graph()
+ parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))
+ parent_session = GraphExecutionState(graph=parent_graph)
+ invocation = parent_session.next()
+ assert isinstance(invocation, CallSavedWorkflowInvocation)
+
+ frame = parent_session.build_workflow_call_frame(invocation.id, invocation.workflow_id)
+ child_session = parent_session.create_child_workflow_execution_state(Graph(), frame)
+ parent_session.begin_waiting_on_workflow_call(frame)
+ parent_session.attach_waiting_workflow_call_child_session(child_session)
+
+ with session_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, status
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ "default",
+ parent_session.model_dump_json(warnings=False),
+ parent_session.id,
+ str(uuid.uuid4()),
+ None,
+ 0,
+ None,
+ None,
+ None,
+ None,
+ "user-1",
+ "in_progress",
+ ),
+ )
+ parent_item_id = cursor.lastrowid
+
+ stale_parent = session_queue.get_queue_item(parent_item_id)
+ session_queue.cancel_queue_item(parent_item_id)
+
+ with pytest.raises(ValueError, match="terminal parent"):
+ session_queue.enqueue_workflow_call_child(stale_parent, child_session)
+
+ with session_queue._db.transaction() as cursor:
+ cursor.execute("SELECT COUNT(*) FROM session_queue WHERE parent_item_id = ?", (parent_item_id,))
+ assert cursor.fetchone()[0] == 0
+
+
+ def test_enqueue_workflow_call_children_publishes_parent_state_before_children(
+ session_queue: SqliteSessionQueue,
+ ) -> None:
+ parent_item_id, _parent_session, child_sessions = _build_waiting_workflow_call_parent(session_queue, child_count=2)
+
+ child_queue_items = session_queue.enqueue_workflow_call_children(
+ parent_queue_item=session_queue.get_queue_item(parent_item_id),
+ child_sessions=[(child_session, None) for child_session in child_sessions],
+ )
+
+ parent_queue_item = session_queue.get_queue_item(parent_item_id)
+ assert parent_queue_item.status == "waiting"
+ assert parent_queue_item.session.waiting_workflow_call_execution is not None
+ assert parent_queue_item.session.waiting_workflow_call_execution.child_item_ids == [
+ child_queue_item.item_id for child_queue_item in child_queue_items
+ ]
+ assert [
+ session_queue.get_queue_item(child_queue_item.item_id).status for child_queue_item in child_queue_items
+ ] == [
+ "pending",
+ "pending",
+ ]
+
+ assert [session_queue.dequeue().item_id for _ in child_queue_items] == [
+ child_queue_item.item_id for child_queue_item in child_queue_items
+ ]
+
+
+ def test_concurrent_workflow_call_child_completions_preserve_both_siblings(
+ session_queue: SqliteSessionQueue,
+ ) -> None:
+ parent_item_id, _parent_session, child_sessions = _build_waiting_workflow_call_parent(session_queue, child_count=2)
+ child_queue_items = session_queue.enqueue_workflow_call_children(
+ parent_queue_item=session_queue.get_queue_item(parent_item_id),
+ child_sessions=[(child_session, None) for child_session in child_sessions],
+ )
+ for child_queue_item in child_queue_items:
+ session_queue.complete_queue_item(child_queue_item.item_id)
+
+ barrier = Barrier(len(child_queue_items))
+ completions = []
+ errors = []
+
+ def record_completion(child_item_id: int, value: int) -> None:
+ try:
+ barrier.wait()
+ completions.append(
+ session_queue.record_workflow_call_child_completion(
+ parent_item_id=parent_item_id,
+ child_item_id=child_item_id,
+ output_values={"result": value},
+ )
+ )
+ except BaseException as error:
+ errors.append(error)
+
+ threads = [
+ Thread(target=record_completion, args=(child_queue_item.item_id, index))
+ for index, child_queue_item in enumerate(child_queue_items, start=1)
+ ]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+
+ assert errors == []
+ assert len(completions) == len(child_queue_items)
+ assert sum(completion is not None and completion.should_resume for completion in completions) == 1
+
+ parent_queue_item = session_queue.get_queue_item(parent_item_id)
+ execution = parent_queue_item.session.waiting_workflow_call_execution
+ assert execution is not None
+ assert set(execution.completed_child_item_ids) == {
+ child_queue_item.item_id for child_queue_item in child_queue_items
+ }
+ assert execution.child_outputs == {
+ child_queue_items[0].item_id: {"result": 1},
+ child_queue_items[1].item_id: {"result": 2},
+ }
+
+
def test_enqueue_workflow_call_child_rejects_full_pending_queue(session_queue: SqliteSessionQueue) -> None:
parent_graph = Graph()
parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))