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): close migration sign-off gaps

JPPhoto1960a608795a
diff --git a/docs/src/content/docs/contributing/call-saved-workflow.md b/docs/src/content/docs/contributing/call-saved-workflow.md
index 782ad8e72f..35458174d6 100644
--- a/docs/src/content/docs/contributing/call-saved-workflow.md
+++ b/docs/src/content/docs/contributing/call-saved-workflow.md
@@ -23,8 +23,10 @@ effect/dependency seam to declare, persist, and resume the call.
The execution-engine refactoring does not change the callable node, saved-workflow, or queue interaction contract.
Internal execution references, tokens, effects, frames, and scheduler records are persistence-only implementation
-metadata. They must remain out of ordinary client-facing responses and generated client schemas. Existing fields,
-requiredness, statuses, events, and client behavior remain compatible. Frontend application behavior is outside this
+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, requiredness, statuses, events, and client behavior remain compatible.
+Frontend application behavior is outside this
execution-engine slice. No code under `invokeai/frontend/...`, including generated `openapi.json` or `schema.ts`, may be
changed by this refactoring; the existing frontend/backend external interface is frozen.
@@ -113,7 +115,7 @@ Implemented runtime scaffolding:
- create the child `GraphExecutionState`
- suspend the parent and enqueue the child queue item
- `WorkflowCallQueueLifecycle` handles queue-visible parent/child lifecycle:
- - run child queue items
+ - dispatch child queue items through the normal session runner
- resume waiting parents after child success
- complete the parent call node with the child `workflow_return` values
- fail suspended parents after child failure and cascade that failure upward through parent call chains
@@ -131,6 +133,9 @@ Implemented runtime scaffolding:
- `root_item_id`
- `workflow_call_depth`
- child workflow executions are now inserted as their own pending queue rows using those columns
+- Child queue rows and the parent's complete waiting-session projection are published in one durable queue
+ transaction. Concurrent child completions update the latest parent session transactionally, so a sibling cannot
+ overwrite another sibling's completion.
- Parent queue items now enter a real `waiting` status while suspended on a child workflow execution.
- `_on_after_run_session()` no longer completes queue items whose sessions are incomplete but waiting.
- Dynamic call arguments now execute end-to-end in the current runner path:
@@ -359,8 +364,8 @@ validation and aggregation seam; it does not add queue columns, statuses, events
- workflow-call child enqueue events use the same owner-aware redaction as ordinary status transitions, even though
they do not pass through `_set_queue_item_status`
-This is now part of the intended user-facing contract, even though the orchestration still lives in
-`WorkflowCallCoordinator`.
+`WorkflowCallCoordinator` owns child setup and enqueueing. `WorkflowCallQueueLifecycle` owns parent resume and terminal
+propagation, using the session queue service for durable row transitions.
### 4b. Batch Child Workflows
@@ -585,7 +590,8 @@ Relevant existing path:
Current insertion points already used:
-- `DefaultSessionRunner.run_node()` detects `call_saved_workflow` and enters boundary state
+- `DefaultSessionRunner.run_node()` supplies the call capability and inputs, invokes the node through the effect-aware
+ path, persists its pending lifecycle effects through `GraphExecutionState.apply()`, then dispatches the queue adapter
- `GraphExecutionState` stores the waiting/call-stack state and attached child session
- `WorkflowCallCoordinator` currently establishes the call boundary and enqueues child workflow executions as real queue
rows
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.md
index 66d34bb9d7..ed3dc40e5d 100644
--- a/docs/src/content/docs/contributing/loop-nodes.md
+++ b/docs/src/content/docs/contributing/loop-nodes.md
@@ -29,9 +29,10 @@ Control-flow nodes remain concrete `BaseInvocation` subclasses. They do not inhe
hierarchy, and they do not return a literal next-node ID. Internal planners and records may share implementation
helpers, while successor readiness is selected from frame-scoped dependencies and effects.
-This is an incremental hybrid, not yet a token-authoritative engine. The execution ledger and internal planners are
-backend persistence details; they do not add author-time ports or change the frontend/backend external contract. No
-file under `invokeai/frontend/...` is part of this refactoring.
+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.
## Core contract
@@ -91,7 +92,7 @@ Nested `For` boundaries are supported recursively when each inner boundary has i
continuation. Independent inner loops must all feed one explicit fan-in continuation; collection concatenation, zipping,
or Cartesian semantics come from the connected collection operation, not from loop scheduling.
-A bounded internal `Iterate` is supported only for the canonical outer-`For` shape: one ordinary preparation node
+A bounded single internal `Iterate` is supported for the canonical outer-`For` shape: one ordinary preparation node
converts `For.item` to the inner collection, one ordinary body node consumes `Iterate.item`, and one `Collect` collapses
that item dimension before the parent `ForReturn`:
@@ -104,9 +105,21 @@ Collect.collection -> ForReturn.output
The fresh generic scheduler admits this exact shape when the outer collection is a non-empty literal or one of the
supported input-driven outer-collection variants, and there is one final consumer of `For.output_collection`. Each
outer frame is isolated, including when the preparation node produces an empty inner collection. A checkpoint after a
-nested iterator boundary restores the generic class-drain state and continues the same frame/stream order. Unsupported
-input-driven outer collections, additional loop or control-flow nodes, escaped body paths, and other mixed shapes
-remain on the compatibility scheduler.
+nested iterator boundary restores the generic class-drain state and continues the same frame/stream order. Valid
+topologies outside these bounds retain compatibility ownership; escaped body paths fail graph validation.
+
+The exact serial two-`Iterate` body is also supported:
+
+```text
+For.item -> preparation1 -> Iterate1.collection
+Iterate1.item -> preparation2 -> Iterate2.collection
+Iterate2.item -> body -> Collect.item
+Collect.collection -> ForReturn.output
+```
+
+Generic admission requires a non-empty literal outer collection, those two ordinary preparation nodes, one ordinary
+body node, and one ordinary `For.output_collection` consumer: nine nodes and nine edges including linkage. This does
+not admit sibling iterators, fan-in, or additional control-flow nodes.
Unsupported shapes, including independent iterator-derived body inputs, mixed nested `For`/`Iterate` bodies, escaping
body paths, ambiguous returns, and arbitrary cyclic graphs, are rejected before execution.
@@ -120,15 +133,16 @@ shape and for explicitly forced compatibility runs:
four-node/four-edge empty input producer with no downstream consumer.
- Canonical two-level nested `For` with a non-empty literal outer collection or supported non-empty input producer;
empty input-driven outer results remain compatibility-owned.
-- Exact two-sibling nested `For` fan-in through non-empty `CollectionConcat`.
+- Exact two-sibling nested `For` fan-in through `CollectionConcat`, with a non-empty literal outer collection.
- Exact serial three-level nested `For`, including its statically non-empty `CollectionConcat` producer variant.
- Exact serial four-level nested `For`.
- Exact bounded outer `For`/`Iterate`/`Collect`.
- Exact serial two-`Iterate` nested outer-`For` shape with one ordinary final consumer.
-Compatibility-owned shapes include legacy snapshots, unsupported input producers, extra nodes or consumers, fan-out,
-malformed linkage or output-scope edges, nested `For` depth five or greater, unsupported sibling or deeper shapes,
-unsupported mixed control flow, and saved-workflow or `If`-containing `For` graphs. No invocation emits or requires a
+Valid shapes outside this admission matrix retain compatibility ownership, including legacy snapshots, unsupported input
+producers, extra nodes or consumers, fan-out, nested `For` depth five or greater, unsupported sibling or deeper shapes,
+and saved-workflow or `If`-containing `For` graphs. Malformed linkage, invalid output-scope edges, and unsupported mixed
+bodies fail graph validation; a compatibility route does not make them executable. No invocation emits or requires a
literal successor node ID. This matrix changes no invocation, API, saved-workflow, frontend, or generated-schema contract.
## Persistence and validation
@@ -228,8 +242,10 @@ the exact one-level nested shape with two `If` nodes where the inner value feeds
consumer, the exact bounded three-`If` chain with direct inner-to-middle-to-outer branch edges, the exact four-`If` nested
chain, or exactly two, exactly three, or exactly four independent ordinary-node sibling `If`s compile opaque, frame-local
activation dependencies in graph state. The three- and four-`If` admissions require `default` edges, all branch inputs
-(`condition`, `true_input`, `false_input`) on each `If`, and no output from inner or middle `If` except its direct nested
-branch edge; the four-`If` chain permits no extra output fan-out. Five-or-more nested `If`s, other fan-out, mixed
+(`condition`, `true_input`, `false_input`) on each `If`. The three-`If` chain permits one extra `middle If.value` edge to
+an ordinary leaf consumer with no outputs; that leaf inherits only the outer branch dependency. Other inner/middle outputs
+must be direct nested branch edges, and the four-`If` chain permits no extra output fan-out. Five-or-more nested `If`s,
+other fan-out, mixed
shapes outside the bounded per-item `Iterate`/`If`/`Collect` topology, loop-containing `For`/`ForReturn`, saved-workflow,
legacy, and
five-or-more sibling shapes use the compatibility scheduler with the dedicated
diff --git a/docs/src/content/docs/features/Workflows/loop-nodes.mdx b/docs/src/content/docs/features/Workflows/loop-nodes.mdx
index 5eb675d377..8ab4e4885f 100644
--- a/docs/src/content/docs/features/Workflows/loop-nodes.mdx
+++ b/docs/src/content/docs/features/Workflows/loop-nodes.mdx
@@ -180,14 +180,17 @@ An `Iterate` can also be used inside a `For` for a bounded inner pass. The inner
`Collect` before the outer `ForReturn`:
```text
-For.item -> Iterate.collection
+For.item -> preparation -> Iterate.collection
Iterate.item -> inner work -> Collect.item
Collect.collection -> ForReturn.output
```
The outer loop waits for the inner `Iterate` and `Collect` to finish, then returns one collection for that outer item.
-Other arrangements, such as multiple internal `Iterate` nodes or an independent external `Iterate` feeding a `For` body,
-are not supported as user-facing workflow shapes. The backend has a bounded
+One exact serial two-`Iterate` body is also supported: `For.item` feeds a preparation node and the first `Iterate`;
+its item feeds a second preparation node and `Iterate`, followed by one work node, one `Collect`, and `ForReturn`.
+For this bounded pattern, use a non-empty literal outer collection and one consumer of `For.output_collection`.
+Other arrangements, such as sibling internal `Iterate` nodes or an independent external `Iterate` feeding a `For` body,
+are unsupported. The backend has a bounded
two-branch execution-planner case for an internal body-mediated fan-in, but
that implementation detail does not expand the supported workflow contract.
diff --git a/invokeai/app/services/session_processor/workflow_call_runtime.py b/invokeai/app/services/session_processor/workflow_call_runtime.py
index f39ee6629a..9b51216134 100644
--- a/invokeai/app/services/session_processor/workflow_call_runtime.py
+++ b/invokeai/app/services/session_processor/workflow_call_runtime.py
@@ -106,29 +106,22 @@ class WorkflowCallCoordinator:
raise ValueError("Execution state is waiting on a workflow call but has no execution metadata.")
queue_item.session.waiting_workflow_call_execution.id = dependency_id
queue_item.session.attach_waiting_workflow_call_child_sessions(child_sessions)
- child_queue_item = None
enqueued_child_item_ids: list[int] = []
try:
- self._session_runner._services.session_queue.save_queue_item_session(queue_item.item_id, queue_item.session)
- for child_result in child_session_results:
- child_queue_item = self._session_runner._services.session_queue.enqueue_workflow_call_child(
- parent_queue_item=queue_item,
- child_session=child_result.session,
- field_values=child_result.field_values,
- )
- enqueued_child_item_ids.append(child_queue_item.item_id)
- queue_item.session.set_waiting_workflow_call_child_item_ids(enqueued_child_item_ids)
- self._session_runner._services.session_queue.save_queue_item_session(queue_item.item_id, queue_item.session)
- self._session_runner._services.session_queue.suspend_queue_item(queue_item.item_id, queue_item=queue_item)
+ child_queue_items = self._session_runner._services.session_queue.enqueue_workflow_call_children(
+ parent_queue_item=queue_item,
+ child_sessions=[(result.session, result.field_values) for result in child_session_results],
+ )
+ enqueued_child_item_ids.extend(child_queue_item.item_id for child_queue_item in child_queue_items)
except Exception as e:
if enqueued_child_item_ids:
self._session_runner._services.session_queue.delete_queue_items_by_id(enqueued_child_item_ids)
queue_item.session.end_waiting_on_workflow_call(status="failed", error_message=str(e))
raise
queue_item.status = "waiting"
- if child_queue_item is None:
+ if not child_queue_items:
raise ValueError("Workflow call did not produce any child executions.")
- return child_queue_item
+ return child_queue_items[-1]
class WorkflowCallQueueLifecycle:
@@ -298,29 +291,16 @@ class WorkflowCallQueueLifecycle:
return
try:
output = self.get_child_workflow_return_output(child_queue_item.session)
- generic_update = parent_queue_item.session.record_generic_child_completion(
- child_queue_item.item_id, output.values
+ completion = self._session_runner._services.session_queue.record_workflow_call_child_completion(
+ parent_item_id=parent_queue_item.item_id,
+ child_item_id=child_queue_item.item_id,
+ output_values=output.values,
)
- if generic_update is not None and not generic_update.changed:
+ if completion is None:
return
- # Keep legacy fields as a durable projection. Generic dependency state owns
- # ordering, idempotency, readiness, and aggregated output decisions.
- legacy_should_resume, legacy_values = (
- parent_queue_item.session.record_waiting_workflow_call_child_completion(
- child_queue_item.item_id, output.values
- )
- )
- if generic_update is None:
- should_resume_parent, aggregated_values = legacy_should_resume, legacy_values
- else:
- should_resume_parent = generic_update.status == "completed"
- generic_values = {
- key: values[0] if len(values) == 1 else values
- for key, values in generic_update.aggregated_outputs.items()
- }
- aggregated_values = generic_values
- if generic_update.status == "completed" and generic_values != legacy_values:
- raise ValueError("Generic child aggregation disagrees with workflow-call aggregation.")
+ parent_queue_item = completion.parent_queue_item
+ should_resume_parent = completion.should_resume
+ aggregated_values = completion.aggregated_values
except Exception as e:
workflow_call_execution = parent_queue_item.session.waiting_workflow_call_execution
if workflow_call_execution is not None:
@@ -339,9 +319,8 @@ class WorkflowCallQueueLifecycle:
self._fail_parent_from_failed_child(parent_queue_item)
return
if not should_resume_parent:
- self._session_runner._services.session_queue.save_queue_item_session(
- parent_queue_item.item_id, parent_queue_item.session
- )
+ # The queue-owned completion transaction already persisted this parent session. Do not
+ # write the returned snapshot again: another child may have committed newer state.
return
parent_queue_item.session.waiting_workflow_call_child_session = child_queue_item.session
waiting_invocation = self.get_waiting_workflow_call_invocation(parent_queue_item)
diff --git a/invokeai/app/services/session_queue/session_queue_base.py b/invokeai/app/services/session_queue/session_queue_base.py
index 02b14f1c7a..dba844ad1d 100644
--- a/invokeai/app/services/session_queue/session_queue_base.py
+++ b/invokeai/app/services/session_queue/session_queue_base.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
+from dataclasses import dataclass
from typing import Any, Coroutine, Optional
from invokeai.app.services.session_queue.session_queue_common import (
@@ -30,6 +31,13 @@ from invokeai.app.services.shared.pagination import CursorPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
+@dataclass(frozen=True)
+class WorkflowCallChildCompletion:
+ parent_queue_item: SessionQueueItem
+ should_resume: bool
+ aggregated_values: dict[str, Any]
+
+
class SessionQueueBase(ABC):
"""Base class for session queue"""
@@ -265,6 +273,22 @@ class SessionQueueBase(ABC):
"""Persists a queue item's session without loading and returning the full queue item."""
pass
+ @abstractmethod
+ def record_workflow_call_child_completion(
+ self, parent_item_id: int, child_item_id: int, output_values: dict[str, Any]
+ ) -> WorkflowCallChildCompletion | None:
+ """Records one child completion against the latest parent session atomically."""
+ pass
+
+ @abstractmethod
+ def enqueue_workflow_call_children(
+ self,
+ parent_queue_item: SessionQueueItem,
+ child_sessions: list[tuple[GraphExecutionState, list[NodeFieldValue] | None]],
+ ) -> list[SessionQueueItem]:
+ """Enqueues child executions and publishes the complete waiting parent state atomically."""
+ pass
+
@abstractmethod
def enqueue_workflow_call_child(
self,
diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.py
index 3fde4ee815..551b6b4efc 100644
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@ -9,7 +9,7 @@ from typing import Any, Optional, Union, cast
from pydantic_core import to_jsonable_python
from invokeai.app.services.invoker import Invoker
-from invokeai.app.services.session_queue.session_queue_base import SessionQueueBase
+from invokeai.app.services.session_queue.session_queue_base import SessionQueueBase, WorkflowCallChildCompletion
from invokeai.app.services.session_queue.session_queue_common import (
DEFAULT_QUEUE_ID,
QUEUE_ITEM_STATUS,
@@ -1491,6 +1491,185 @@ class SqliteSessionQueue(SessionQueueBase):
self.save_queue_item_session(item_id, session)
return self.get_queue_item(item_id)
+ def record_workflow_call_child_completion(
+ self, parent_item_id: int, child_item_id: int, output_values: dict[str, Any]
+ ) -> WorkflowCallChildCompletion | None:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT *
+ FROM session_queue
+ WHERE item_id = ?
+ """,
+ (parent_item_id,),
+ )
+ row = cast(sqlite3.Row | None, cursor.fetchone())
+ if row is None:
+ raise SessionQueueItemNotFoundError(f"No queue item with id {parent_item_id}")
+ parent_queue_item, readable = self._hydrate_queue_item(dict(row), quarantine=False)
+ if not readable:
+ raise ValueError("Unable to record workflow call child completion for an unreadable parent session.")
+ if parent_queue_item.status in ("completed", "failed", "canceled"):
+ return None
+
+ execution = parent_queue_item.session.waiting_workflow_call_execution
+ if execution is not None and child_item_id in execution.completed_child_item_ids:
+ return None
+ generic_update = parent_queue_item.session.record_generic_child_completion(child_item_id, output_values)
+ if generic_update is not None and not generic_update.changed:
+ return None
+ legacy_should_resume, legacy_values = (
+ parent_queue_item.session.record_waiting_workflow_call_child_completion(child_item_id, output_values)
+ )
+ if generic_update is None:
+ should_resume_parent, aggregated_values = legacy_should_resume, legacy_values
+ else:
+ should_resume_parent = generic_update.status == "completed"
+ aggregated_values = {
+ key: values[0] if len(values) == 1 else values
+ for key, values in generic_update.aggregated_outputs.items()
+ }
+ if generic_update.status == "completed" and aggregated_values != legacy_values:
+ raise ValueError("Generic child aggregation disagrees with workflow-call aggregation.")
+
+ session_json = json.dumps(dump_execution_state(parent_queue_item.session), default=to_jsonable_python)
+ cursor.execute(
+ """--sql
+ UPDATE session_queue
+ SET session = ?
+ WHERE item_id = ?
+ """,
+ (session_json, parent_item_id),
+ )
+ if cursor.rowcount == 0:
+ raise SessionQueueItemNotFoundError(f"No queue item with id {parent_item_id}")
+
+ return WorkflowCallChildCompletion(
+ parent_queue_item=parent_queue_item,
+ should_resume=should_resume_parent,
+ aggregated_values=aggregated_values,
+ )
+
+ def enqueue_workflow_call_children(
+ self,
+ parent_queue_item: SessionQueueItem,
+ child_sessions: list[tuple[GraphExecutionState, list[NodeFieldValue] | None]],
+ ) -> list[SessionQueueItem]:
+ workflow_call_execution = parent_queue_item.session.waiting_workflow_call_execution
+ if workflow_call_execution is None:
+ raise ValueError("Parent queue item is missing active workflow call execution metadata.")
+ if not child_sessions:
+ raise ValueError("Workflow call must enqueue at least one child execution.")
+
+ serialized_children = [
+ (
+ json.dumps(dump_execution_state(child_session), default=to_jsonable_python),
+ json.dumps(field_values, default=to_jsonable_python) if field_values is not None else None,
+ )
+ for child_session, field_values in child_sessions
+ ]
+ root_item_id = parent_queue_item.root_item_id or parent_queue_item.item_id
+ child_item_ids: list[int] = []
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT status
+ FROM session_queue
+ WHERE item_id = ?
+ """,
+ (parent_queue_item.item_id,),
+ )
+ parent_status_row = cursor.fetchone()
+ if parent_status_row is None:
+ raise SessionQueueItemNotFoundError(f"No queue item with id {parent_queue_item.item_id}")
+ if parent_status_row[0] in ("completed", "failed", "canceled"):
+ raise ValueError("Cannot enqueue workflow call children for a terminal parent queue item.")
+
+ cursor.execute(
+ """--sql
+ SELECT COUNT(*)
+ FROM session_queue
+ WHERE queue_id = ? AND status = 'pending'
+ """,
+ (parent_queue_item.queue_id,),
+ )
+ pending_count = cast(int, cursor.fetchone()[0])
+ max_queue_size = self.__invoker.services.configuration.max_queue_size
+ if pending_count + len(child_sessions) > max_queue_size:
+ raise TooManySessionsError(
+ "call_saved_workflow exceeds remaining queue capacity for child workflow executions"
+ )
+
+ for (session_json, field_values_json), (child_session, _field_values) in zip(
+ serialized_children, child_sessions, strict=True
+ ):
+ 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,
+ workflow_call_id,
+ parent_item_id,
+ parent_session_id,
+ root_item_id,
+ workflow_call_depth,
+ status
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
+ """,
+ (
+ parent_queue_item.queue_id,
+ session_json,
+ child_session.id,
+ parent_queue_item.batch_id,
+ field_values_json,
+ parent_queue_item.priority,
+ None,
+ parent_queue_item.origin,
+ parent_queue_item.destination,
+ None,
+ parent_queue_item.user_id,
+ workflow_call_execution.id,
+ parent_queue_item.item_id,
+ parent_queue_item.session_id,
+ root_item_id,
+ workflow_call_execution.depth,
+ ),
+ )
+ child_item_ids.append(cast(int, cursor.lastrowid))
+
+ parent_queue_item.session.set_waiting_workflow_call_child_item_ids(child_item_ids)
+ session_json = json.dumps(dump_execution_state(parent_queue_item.session), default=to_jsonable_python)
+ cursor.execute(
+ """--sql
+ UPDATE session_queue
+ SET session = ?, status = 'waiting', status_sequence = COALESCE(status_sequence, 0) + 1
+ WHERE item_id = ?
+ """,
+ (session_json, parent_queue_item.item_id),
+ )
+ if cursor.rowcount == 0:
+ raise SessionQueueItemNotFoundError(f"No queue item with id {parent_queue_item.item_id}")
+
+ parent_queue_item.status = "waiting"
+ child_queue_items = [self.get_queue_item(item_id) for item_id in child_item_ids]
+ for queue_item in [self.get_queue_item(parent_queue_item.item_id), *child_queue_items]:
+ batch_status = self.get_batch_status(queue_id=queue_item.queue_id, batch_id=queue_item.batch_id)
+ queue_status = self.get_queue_status(
+ queue_id=queue_item.queue_id, user_id=queue_item.user_id, acting_user_id=queue_item.user_id
+ )
+ self.__invoker.services.events.emit_queue_item_status_changed(queue_item, batch_status, queue_status)
+ return child_queue_items
+
def enqueue_workflow_call_child(
self,
parent_queue_item: SessionQueueItem,
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 37b6195981..b894e72b96 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -18,8 +18,9 @@ dependencies in `GraphExecutionState`; unsupported fresh shapes use the compatib
`_IfActivationController` fallback, while legacy snapshots retain their generic compatibility projection.
Current fresh sibling support includes exactly four independent `If`s with no nesting, fan-out, or other control-flow
nodes. The bounded three-`If` chain requires direct `default` edges, all three `If`s to have `condition`, `true_input`,
-and `false_input` inputs, and inner/middle `If`s to have no output except their direct nested branch edge. The exact
-four-`If` chain has the same input and direct-edge requirements, with no extra
+and `false_input` inputs. The inner `If` has only its direct nested branch output; the middle `If.value` may also feed
+one ordinary leaf consumer with no outputs. That leaf inherits the outer branch dependency, not middle-`If` polarity.
+The exact four-`If` chain has the same input and direct-edge requirements, with no extra
output fan-out. Five or more nested `If`s, other fan-out, mixed graphs outside
the bounded per-item `Iterate`/`If`/`Collect` topology, loop-containing,
saved-workflow, legacy, and five-or-more sibling shapes remain on the
@@ -371,8 +372,9 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre
### 4.2 Core methods
-- `next()` Returns the next ready exec node. If none are ready, it asks the materializer to expand more source nodes and
- then retries. If the execution state is paused on a workflow call boundary, it returns `None` without scheduling more
+- `next()` Returns the next ready exec node. If none are ready, it asks the admitted planner or compatibility materializer
+ to expand more source nodes and then retries. If the execution state is paused on a workflow call boundary, it returns
+ `None` without scheduling more
work. Before returning a node, the runtime helper deep-copies inbound values into the node fields.
- `complete(node_id, output)` is the compatibility completion boundary. For a first JSON-safe completion it delegates
validation and the atomic scheduler/ledger transition to `apply()`, including output tokens and synthetic
@@ -403,7 +405,7 @@ rehydration, every activation token is bound to a currently prepared owner and i
declared port, value, canonical token id, mapping key, and known frame fields must match. Unknown extra frame metadata
remains forward-compatible.
For a fresh generic `If` graph with one ordinary-node `If`, the exact one-level nested shape described above, the exact
-bounded three-`If` inner/middle/outer chain, the exact four-`If` nested chain,
+bounded three-`If` inner/middle/outer chain (including its single middle-value leaf consumer), the exact four-`If` nested chain,
or exactly two, exactly three, or exactly four independent sibling `If`s,
`GraphExecutionState` compiles opaque, frame-local activation-dependency records privately on each branch-local plan
node. Five-or-more nesting, five-or-more sibling `If`s, other fan-out, mixed graphs outside the bounded per-item
@@ -653,8 +655,10 @@ 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. 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;
+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.
### 4.4 Compatibility preparation (`_prepare()`)
@@ -706,9 +710,10 @@ materialization.
for its frame. Fresh admission prevents rejected branch nodes from reaching this queue. For direct `Collect` nodes,
the adapter also requires available Iterate streams to be closed. Compatibility uses the same opaque activation
dependencies; legacy skipped metadata remains for old snapshots.
-- `_get_next_node()` uses the generic scheduler for ordinary static DAGs and legacy-shaped `If` graphs, projecting its
- deterministic class/frame order into the compatibility queues. Loop and saved-workflow control-flow graphs use `_active_class`
- and the legacy class queues. No batch-size or fairness cap is currently implemented.
+- `_get_next_node()` uses the generic scheduler for ordinary static DAGs, legacy-shaped `If` graphs, and the admitted
+ fresh control-flow shapes described above, projecting deterministic class/frame order into the compatibility queues.
+ Fallback control-flow graphs, including saved-workflow calls, use `_active_class` and the legacy class queues.
+ No batch-size or fairness cap is currently implemented.
#### 4.5.1 Indegree (what it is and how it's used)
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index f064745e5d..1a2e267f2e 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -33,7 +33,7 @@ from pydantic import (
model_validator, # noqa: F401
)
from pydantic.fields import Field
-from pydantic.json_schema import JsonSchemaValue # noqa: F401
+from pydantic.json_schema import JsonSchemaValue, SkipJsonSchema # noqa: F401
from pydantic_core import PydanticSerializationError, core_schema # noqa: F401
# Importing * is bad karma but needed here for node detection
@@ -288,22 +288,22 @@ class GraphExecutionState(BaseModel):
description="The iteration coordinates of each prepared execution node",
default_factory=dict,
)
- execution_refs: dict[str, ExecutionReference] = Field(
+ execution_refs: SkipJsonSchema[dict[str, ExecutionReference]] = Field(
default_factory=dict,
description="Stable frame-aware references for prepared execution nodes",
exclude=True,
)
- execution_tokens: dict[str, ExecutionToken] = Field(
+ execution_tokens: SkipJsonSchema[dict[str, ExecutionToken]] = Field(
default_factory=dict,
description="Data tokens produced by prepared execution output ports",
exclude=True,
)
- execution_effects: dict[str, list[Any]] = Field(
+ execution_effects: SkipJsonSchema[dict[str, list[Any]]] = Field(
default_factory=dict,
description="Effects accepted for each execution reference",
exclude=True,
)
- execution_child_dependencies: dict[str, ChildDependencyRecord] = Field(
+ execution_child_dependencies: SkipJsonSchema[dict[str, ChildDependencyRecord]] = Field(
default_factory=dict,
description="Durable generic child dependency records",
exclude=True,
diff --git a/invokeai/app/util/custom_openapi.py b/invokeai/app/util/custom_openapi.py
index f674fa7621..2e365020ee 100644
--- a/invokeai/app/util/custom_openapi.py
+++ b/invokeai/app/util/custom_openapi.py
@@ -17,6 +17,17 @@ from invokeai.backend.util.logging import InvokeAILogger
logger = InvokeAILogger.get_logger()
+_INTERNAL_EXECUTION_SCHEMA_NAMES = frozenset(
+ {
+ "ChildCompletion",
+ "ChildDependencyRecord",
+ "ChildExecutionRecord",
+ "ExecutionFrame",
+ "ExecutionReference",
+ "ExecutionToken",
+ }
+)
+
def move_defs_to_top_level(openapi_schema: dict[str, Any], component_schema: dict[str, Any]) -> None:
"""Moves a component schema's $defs to the top level of the openapi schema. Useful when generating a schema
@@ -47,6 +58,50 @@ def normalize_path_defaults(node: Any) -> None:
normalize_path_defaults(v)
+def remove_unreferenced_internal_execution_schemas(openapi_schema: dict[str, Any]) -> None:
+ """Remove internal execution definitions when no public schema references them.
+
+ Pydantic can leave definitions for fields annotated with ``SkipJsonSchema`` in
+ the OpenAPI component map. Keep an internal definition if a public schema
+ references it, including through another internal definition; otherwise it
+ must not appear in the client-facing schema.
+ """
+
+ schemas = openapi_schema.get("components", {}).get("schemas", {})
+ if not schemas:
+ return
+
+ def collect_refs(value: Any, refs: set[str]) -> None:
+ if isinstance(value, dict):
+ ref = value.get("$ref")
+ if isinstance(ref, str) and ref.startswith("#/components/schemas/"):
+ refs.add(ref.removeprefix("#/components/schemas/"))
+ for child in value.values():
+ collect_refs(child, refs)
+ elif isinstance(value, list):
+ for child in value:
+ collect_refs(child, refs)
+
+ refs: set[str] = set()
+ for schema_name, schema in schemas.items():
+ if schema_name not in _INTERNAL_EXECUTION_SCHEMA_NAMES:
+ collect_refs(schema, refs)
+ collect_refs(openapi_schema.get("paths", {}), refs)
+
+ required_internal = refs & _INTERNAL_EXECUTION_SCHEMA_NAMES
+ while required_internal:
+ nested_refs: set[str] = set()
+ for schema_name in required_internal:
+ collect_refs(schemas.get(schema_name), nested_refs)
+ new_required = nested_refs & _INTERNAL_EXECUTION_SCHEMA_NAMES - required_internal
+ if not new_required:
+ break
+ required_internal.update(new_required)
+
+ for schema_name in _INTERNAL_EXECUTION_SCHEMA_NAMES - required_internal:
+ schemas.pop(schema_name, None)
+
+
def get_openapi_func(
app: FastAPI, post_transform: Optional[Callable[[dict[str, Any]], dict[str, Any]]] = None
) -> Callable[[], dict[str, Any]]:
@@ -143,6 +198,7 @@ def get_openapi_func(
if post_transform is not None:
openapi_schema = post_transform(openapi_schema)
+ remove_unreferenced_internal_execution_schemas(openapi_schema)
normalize_path_defaults(openapi_schema)
openapi_schema["components"]["schemas"] = dict(sorted(openapi_schema["components"]["schemas"].items()))
diff --git 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
index edf678f0df..9123397ade 100644
--- 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,6 +1,7 @@
"""Tests for workflow-call relationship metadata on session_queue items."""
import uuid
+from threading import Barrier, Thread
import pytest
@@ -93,6 +94,22 @@ def _insert_queue_item(
return cursor.lastrowid
+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)
@@ -251,6 +268,87 @@ def test_enqueue_workflow_call_child_persists_pending_child_queue_item(session_q
assert child_queue_item.session_id == child_session.id
+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"))
diff --git a/tests/app/services/shared/test_graph_models.py b/tests/app/services/shared/test_graph_models.py
index e738487152..50c56d4979 100644
--- a/tests/app/services/shared/test_graph_models.py
+++ b/tests/app/services/shared/test_graph_models.py
@@ -3,6 +3,7 @@ import sys
import textwrap
import pytest
+from fastapi import FastAPI
from pydantic import TypeAdapter, model_validator
from pydantic.json_schema import models_json_schema
@@ -12,6 +13,29 @@ from invokeai.app.invocations.math import AddInvocation
from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem
from invokeai.app.services.shared import graph as graph_facade
from invokeai.app.services.shared import graph_models, graph_validation
+from invokeai.app.util.custom_openapi import get_openapi_func
+
+
+def test_queue_openapi_excludes_runtime_ledgers_and_internal_components() -> None:
+ app = FastAPI(separate_input_output_schemas=False)
+ app.get("/queue-item", response_model=SessionQueueItem)(lambda: None)
+ app.openapi = get_openapi_func(app)
+
+ schemas = app.openapi()["components"]["schemas"]
+ assert {
+ "execution_refs",
+ "execution_tokens",
+ "execution_effects",
+ "execution_child_dependencies",
+ }.isdisjoint(schemas["GraphExecutionState"]["properties"])
+ assert {
+ "ExecutionFrame",
+ "ExecutionReference",
+ "ExecutionToken",
+ "ChildCompletion",
+ "ChildDependencyRecord",
+ "ChildExecutionRecord",
+ }.isdisjoint(schemas)
def test_graph_facade_reexports_authoring_graph_boundary() -> None:
diff --git a/tests/app/services/test_workflow_call_runtime.py b/tests/app/services/test_workflow_call_runtime.py
index 4f5f211db2..fa309f1666 100644
--- a/tests/app/services/test_workflow_call_runtime.py
+++ b/tests/app/services/test_workflow_call_runtime.py
@@ -31,6 +31,10 @@ def test_workflow_call_queue_lifecycle_resumes_parent_from_completed_child(monke
workflow_call_tests.test_workflow_call_queue_lifecycle_resumes_parent_from_completed_child(monkeypatch)
+def test_nonfinal_child_completion_does_not_rewrite_the_persisted_parent_session(monkeypatch) -> None:
+ workflow_call_tests.test_nonfinal_child_completion_does_not_rewrite_the_persisted_parent_session(monkeypatch)
+
+
def test_resume_waiting_workflow_call_applies_parent_output_to_execution_ledger(monkeypatch) -> None:
workflow_call_tests.test_resume_waiting_workflow_call_applies_parent_output_to_execution_ledger(monkeypatch)
diff --git a/tests/app/services/workflow_call_test_utils.py b/tests/app/services/workflow_call_test_utils.py
index 0fc00a0164..7e74511a2a 100644
--- a/tests/app/services/workflow_call_test_utils.py
+++ b/tests/app/services/workflow_call_test_utils.py
@@ -25,6 +25,7 @@ from invokeai.app.services.session_processor.workflow_call_runtime import (
WorkflowCallCoordinator,
WorkflowCallQueueLifecycle,
)
+from invokeai.app.services.session_queue.session_queue_base import WorkflowCallChildCompletion
from invokeai.app.services.session_queue.session_queue_common import SessionQueueItemNotFoundError
from invokeai.app.services.shared.execution_effects import ExecutionEffectsRecorder, ExecutionInterface
from invokeai.app.services.shared.graph import Graph, GraphExecutionState, WorkflowCallFrame
@@ -992,6 +993,46 @@ class _DummySessionQueue:
queue_item.session = session
self.session_updates.append((item_id, session))
+ def enqueue_workflow_call_children(self, parent_queue_item, child_sessions):
+ self._ensure_queue_item(parent_queue_item.item_id, parent_queue_item.session)
+ child_queue_items = []
+ try:
+ for child_session, field_values in child_sessions:
+ child_queue_items.append(
+ self.enqueue_workflow_call_child(parent_queue_item, child_session, field_values)
+ )
+ except Exception:
+ self.delete_queue_items_by_id([child_queue_item.item_id for child_queue_item in child_queue_items])
+ raise
+ parent_queue_item.session.set_waiting_workflow_call_child_item_ids(
+ [child_queue_item.item_id for child_queue_item in child_queue_items]
+ )
+ parent_queue_item.status = "waiting"
+ self.waiting_item_ids.append(parent_queue_item.item_id)
+ return child_queue_items
+
+ def record_workflow_call_child_completion(self, parent_item_id, child_item_id, output_values):
+ parent_queue_item = self.get_queue_item(parent_item_id)
+ if parent_queue_item.status in ("completed", "failed", "canceled"):
+ return None
+ generic_update = parent_queue_item.session.record_generic_child_completion(child_item_id, output_values)
+ if generic_update is not None and not generic_update.changed:
+ return None
+ legacy_should_resume, legacy_values = parent_queue_item.session.record_waiting_workflow_call_child_completion(
+ child_item_id, output_values
+ )
+ if generic_update is None:
+ should_resume_parent, aggregated_values = legacy_should_resume, legacy_values
+ else:
+ should_resume_parent = generic_update.status == "completed"
+ aggregated_values = {
+ key: values[0] if len(values) == 1 else values
+ for key, values in generic_update.aggregated_outputs.items()
+ }
+ if generic_update.status == "completed" and aggregated_values != legacy_values:
+ raise ValueError("Generic child aggregation disagrees with workflow-call aggregation.")
+ return WorkflowCallChildCompletion(parent_queue_item, should_resume_parent, aggregated_values)
+
def suspend_queue_item(self, item_id: int, queue_item=None):
self._raise_if_not_found(item_id)
queue_item = queue_item or self._ensure_queue_item(item_id, None)
@@ -1666,6 +1707,59 @@ def test_workflow_call_queue_lifecycle_resumes_parent_from_completed_child(
]
+def test_nonfinal_child_completion_does_not_rewrite_the_persisted_parent_session(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ session_queue = _DummySessionQueue()
+ runner, _events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)
+ lifecycle = WorkflowCallQueueLifecycle(runner)
+
+ parent_graph = Graph()
+ parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))
+ parent_session = GraphExecutionState(graph=parent_graph)
+ parent_invocation = parent_session.next()
+ assert isinstance(parent_invocation, CallSavedWorkflowInvocation)
+ frame = parent_session.build_workflow_call_frame(parent_invocation.id, "workflow-a")
+ parent_session.begin_waiting_on_workflow_call(frame)
+
+ child_sessions = [parent_session.create_child_workflow_execution_state(Graph(), frame) for _ in range(2)]
+ parent_session.attach_waiting_workflow_call_child_sessions(child_sessions)
+ parent_session.set_waiting_workflow_call_child_item_ids([100, 101])
+ parent_queue_item = SimpleNamespace(
+ item_id=1,
+ status="waiting",
+ session=parent_session,
+ session_id=parent_session.id,
+ user_id="user-1",
+ queue_id="default",
+ batch_id="batch-1",
+ )
+ session_queue.add_queue_item(parent_queue_item)
+
+ child_graph = Graph()
+ child_graph.add_node(WorkflowReturnInvocation(id="return"))
+ child_session = GraphExecutionState(graph=child_graph)
+ child_return = child_session.next()
+ assert isinstance(child_return, WorkflowReturnInvocation)
+ child_session.complete(child_return.id, WorkflowReturnOutput(values={"result": 1}))
+ child_queue_item = SimpleNamespace(
+ item_id=100,
+ status="completed",
+ session=child_session,
+ session_id=child_session.id,
+ parent_item_id=1,
+ )
+
+ def fail_stale_save(*_args: Any, **_kwargs: Any) -> None:
+ raise AssertionError("non-final child completion rewrote the persisted parent session")
+
+ monkeypatch.setattr(session_queue, "save_queue_item_session", fail_stale_save)
+ lifecycle._resume_parent_from_completed_child(child_queue_item)
+
+ assert parent_session.waiting_workflow_call_execution is not None
+ assert parent_session.waiting_workflow_call_execution.completed_child_item_ids == [100]
+
+
def test_resume_waiting_workflow_call_applies_parent_output_to_execution_ledger(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/tests/app/util/test_custom_openapi.py b/tests/app/util/test_custom_openapi.py
index e0f054917a..45d9dc8a66 100644
--- a/tests/app/util/test_custom_openapi.py
+++ b/tests/app/util/test_custom_openapi.py
@@ -3,7 +3,11 @@ from pydantic import create_model
from invokeai.app.invocations.baseinvocation import InvocationRegistry
from invokeai.app.services.config.config_default import InvokeAIAppConfig
-from invokeai.app.util.custom_openapi import get_openapi_func, normalize_path_defaults
+from invokeai.app.util.custom_openapi import (
+ get_openapi_func,
+ normalize_path_defaults,
+ remove_unreferenced_internal_execution_schemas,
+)
class _FakeOutput:
@@ -88,3 +92,21 @@ def test_path_defaults_are_normalized_to_forward_slashes() -> None:
assert (
schema["properties"]["nested_path"]["oneOf"][0]["properties"]["cache_dir"]["default"] == "models/.nested_cache"
)
+
+
+def test_internal_execution_schemas_are_retained_when_publicly_referenced() -> None:
+ schema = {
+ "paths": {},
+ "components": {
+ "schemas": {
+ "Public": {"properties": {"reference": {"$ref": "#/components/schemas/ExecutionReference"}}},
+ "ExecutionReference": {"properties": {"frame": {"$ref": "#/components/schemas/ExecutionFrame"}}},
+ "ExecutionFrame": {},
+ "ExecutionToken": {},
+ }
+ },
+ }
+
+ remove_unreferenced_internal_execution_schemas(schema)
+
+ assert set(schema["components"]["schemas"]) == {"Public", "ExecutionReference", "ExecutionFrame"}
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index a421265076..684eb2544e 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -263,9 +263,7 @@ def test_graph_state_apply_stores_stable_frame_tokens_and_effects():
assert state.execution_effects[ref.reference_id] == [{"owner_node_id": node.id, "source_port": "value"}]
assert state.execution_tokens[f"{ref.reference_id}:value"].value == 3
- restored = TypeAdapter(GraphExecutionState).validate_python(
- state.model_dump(mode="json", warnings=False), strict=False
- )
+ 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
@@ -439,7 +437,7 @@ def test_graph_state_apply_records_generic_effect_stream_and_rehydrates_it():
assert streams[0].closed
assert streams[0].values == (3,)
- restored = TypeAdapter(GraphExecutionState).validate_json(state.model_dump_json(), strict=False)
+ restored = load_execution_state(dump_execution_state(state))
restored_streams = list(restored._generic_runtime().streams.values())
assert len(restored_streams) == 1
assert restored_streams[0].closed
@@ -1078,11 +1076,11 @@ def test_graph_state_rehydration_rejects_persisted_effect_token_from_another_own
output,
effects=[{"kind": "emit", "token": {"node_id": node.id, "field": "value", "value": 3}}],
)
- snapshot = state.model_dump(mode="json")
+ snapshot = dump_execution_state(state)
snapshot["execution_effects"][ref.reference_id][0]["token"]["node_id"] = "other"
with pytest.raises(ValueError, match="not owned"):
- TypeAdapter(GraphExecutionState).validate_python(snapshot, strict=False)
+ load_execution_state(snapshot)
def test_graph_state_apply_does_not_complete_when_effect_persistence_preparation_fails():
@@ -1221,12 +1219,13 @@ def test_graph_state_rehydrates_execution_refs_for_legacy_state():
state = GraphExecutionState(graph=graph)
node = state.next()
assert node is not None
- legacy_payload = state.model_dump(mode="json", warnings=False)
+ legacy_payload = dump_execution_state(state)
+ legacy_payload.pop("execution_state_version")
legacy_payload.pop("execution_refs")
legacy_payload.pop("execution_tokens")
legacy_payload.pop("execution_effects")
- restored = TypeAdapter(GraphExecutionState).validate_python(legacy_payload, strict=False)
+ restored = load_execution_state(legacy_payload)
ref = restored.get_execution_ref(node.id)
assert ref.state_id == restored.id
@@ -5076,7 +5075,7 @@ def test_if_snapshot_rejects_conflicting_activation_tokens():
state = GraphExecutionState(graph=graph)
execute_all_nodes(state)
- snapshot = state.model_dump(mode="json")
+ snapshot = dump_execution_state(state)
activation_id, activation = next(
(token_id, token)
for token_id, token in snapshot["execution_tokens"].items()
@@ -5091,7 +5090,7 @@ def test_if_snapshot_rejects_conflicting_activation_tokens():
}
with pytest.raises(ValueError, match="conflicting activation tokens"):
- TypeAdapter(GraphExecutionState).validate_python(snapshot, strict=False)
+ load_execution_state(snapshot)
def test_if_snapshot_rejects_activation_token_with_contradictory_value():
@@ -5106,7 +5105,7 @@ def test_if_snapshot_rejects_activation_token_with_contradictory_value():
state = GraphExecutionState(graph=graph)
execute_all_nodes(state)
- snapshot = state.model_dump(mode="json")
+ snapshot = dump_execution_state(state)
token_id, token = next(
(token_id, token)
for token_id, token in snapshot["execution_tokens"].items()
@@ -5115,7 +5114,7 @@ def test_if_snapshot_rejects_activation_token_with_contradictory_value():
snapshot["execution_tokens"][token_id] = {**token, "value": "false_input"}
with pytest.raises(ValueError, match="stale value"):
- TypeAdapter(GraphExecutionState).validate_python(snapshot, strict=False)
+ load_execution_state(snapshot)
def test_empty_iterate_graph_records_a_closed_empty_stream():