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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(execution): extract graph model records
JPPhotoc4d6450d0673
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 7996572ef6..8c62de5ef3 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -33,7 +33,7 @@ from pydantic import (TypeAdapter,ValidationError,field_validator,- model_validator,+ model_validator, # noqa: F401)from pydantic.fields import Fieldfrom pydantic.json_schema import JsonSchemaValue@@ -84,6 +84,20 @@ from invokeai.app.services.shared.execution_engine.scheduler import (ExecutionPlan,ExecutionScheduler,)+from invokeai.app.services.shared.graph_models import (+ Edge, # noqa: F401+ EdgeConnection, # noqa: F401+ ExecutionFrame, # noqa: F401+ ExecutionRef, # noqa: F401+ ExecutionReference, # noqa: F401+ ExecutionToken, # noqa: F401+ PreparedExecState, # noqa: F401+ PreparedExecutionRef, # noqa: F401+ WorkflowCallExecution, # noqa: F401+ WorkflowCallFrame, # noqa: F401+ WorkflowCallParentRef, # noqa: F401+ WorkflowCallStatus, # noqa: F401+)from invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.app.util.misc import uuid_string@@ -147,90 +161,6 @@ class _SupportedNestedIterateBody:collect_node_id: str-class EdgeConnection(BaseModel):- model_config = ConfigDict(frozen=True)-- node_id: str = Field(description="The id of the node for this edge connection")- field: str = Field(description="The field for this connection")-- def __eq__(self, other):- return (- isinstance(other, self.__class__)- and getattr(other, "node_id", None) == self.node_id- and getattr(other, "field", None) == self.field- )-- def __hash__(self):- return hash(f"{self.node_id}.{self.field}")---class Edge(BaseModel):- model_config = ConfigDict(frozen=True)-- type: Literal["default", "loop_linkage"] = Field(- default="default",- description="The kind of relationship represented by this edge",- )- source: EdgeConnection = Field(description="The connection for the edge's from node and field")- destination: EdgeConnection = Field(description="The connection for the edge's to node and field")-- def __str__(self):- return f"{self.source.node_id}.{self.source.field} -> {self.destination.node_id}.{self.destination.field}"---PreparedExecState = Literal["pending", "ready", "executed", "skipped"]-WorkflowCallStatus = Literal["waiting_for_child", "running_child", "completed", "failed"]---class WorkflowCallFrame(BaseModel):- """Represents one workflow-call frame in a nested call chain."""-- prepared_call_node_id: str = Field(description="The prepared exec node id for the call site.")- source_call_node_id: str = Field(description="The source graph node id for the call site.")- workflow_id: str = Field(description="The saved workflow being called.")- depth: int = Field(description="The 1-based depth of this call frame.", ge=1)---class WorkflowCallExecution(BaseModel):- """Tracks one parent/child workflow-call relationship and its lifecycle."""-- id: str = Field(description="The workflow-call execution id.", default_factory=uuid_string)- parent_session_id: str = Field(description="The parent graph execution state id.")- child_session_id: Optional[str] = Field(default=None, description="The child graph execution state id, if any.")- prepared_call_node_id: str = Field(description="The prepared exec node id for the parent call site.")- source_call_node_id: str = Field(description="The source graph node id for the parent call site.")- workflow_id: str = Field(description="The saved workflow being called.")- depth: int = Field(description="The 1-based depth of this call frame.", ge=1)- status: WorkflowCallStatus = Field(description="The current workflow-call lifecycle state.")- error_message: Optional[str] = Field(default=None, description="Failure reason, if the call failed.")- child_session_ids: list[str] = Field(default_factory=list, description="All child graph execution state ids.")- child_item_ids: list[int] = Field(default_factory=list, description="Child queue item ids in enqueue order.")- expected_child_count: int = Field(default=1, ge=1, description="The number of child executions for this call.")- completed_child_item_ids: list[int] = Field(- default_factory=list,- description="The child queue item ids whose workflow_return outputs have been aggregated.",- )- aggregated_values: dict[str, list[Any]] = Field(- default_factory=dict,- description="The aggregated workflow_return values accumulated from child executions.",- )- child_outputs: dict[int, dict[str, Any]] = Field(- default_factory=dict,- description="Workflow return values keyed by child queue item id.",- )---class WorkflowCallParentRef(BaseModel):- """Reference from a child execution state back to its parent workflow-call relationship."""-- workflow_call_id: str = Field(description="The workflow-call execution id.")- parent_session_id: str = Field(description="The parent graph execution state id.")- prepared_call_node_id: str = Field(description="The prepared exec node id for the parent call site.")- source_call_node_id: str = Field(description="The source graph node id for the parent call site.")- workflow_id: str = Field(description="The saved workflow being called.")- depth: int = Field(description="The 1-based depth of this call frame.", ge=1)--@dataclassclass _PreparedExecNodeMetadata:"""Cached metadata for a materialized execution node."""@@ -3071,76 +3001,6 @@ class AnyInvocationOutput(BaseInvocationOutput):return {"oneOf": oneOf}-class ExecutionFrame(BaseModel):- """Stable execution location for a prepared node."""-- frame_id: str = Field(default="", description="Stable frame identifier")- state_id: str = Field(default="", description="Owning graph execution state id")- iteration_path: tuple[int, ...] = Field(default_factory=tuple, description="Loop iteration coordinates")- workflow_call_depth: int = Field(default=0, ge=0, description="Nested workflow-call depth")-- model_config = ConfigDict(extra="allow")---class ExecutionReference(BaseModel):- """Stable, frame-aware reference to one prepared execution node.-- This intentionally stays independent from invocation-context/effect models. The execution engine can reconcile- this small compatibility type with a richer protocol later without changing persisted graph state.- """-- reference_id: str = Field(default="", description="Stable reference identifier")- state_id: str = Field(default="", description="Owning graph execution state id")- exec_node_id: str = Field(default="", description="Prepared execution node id")- source_node_id: str = Field(default="", description="Authoring graph node id")- frame: ExecutionFrame = Field(default_factory=ExecutionFrame, description="Execution frame")- effect_count: Optional[int] = Field(default=None, ge=0, description="Expected effect count, if declared")-- model_config = ConfigDict(extra="allow")-- @property- def id(self) -> str:- return self.reference_id-- @property- def node_id(self) -> str:- return self.exec_node_id---class ExecutionToken(BaseModel):- """Data token owned by one prepared output port.-- Tokens contain no graph edge or association metadata. In particular, loop-linkage edges never become data- tokens.- """-- token_id: str = Field(description="Stable token identifier")- reference_id: str = Field(description="Owning execution reference id")- owner_node_id: str = Field(description="Prepared node that produced the token")- port: str = Field(description="Output port name")- frame: ExecutionFrame = Field(description="Frame that produced the token")- value: Any = Field(description="Output port value")- token_kind: Literal["data", "activation", "stream_end"] = Field(default="data")-- @model_validator(mode="before")- @classmethod- def _restore_excluded_null_value(cls, value: Any) -> Any:- """Allow exclude-none runtime snapshots to hydrate nullable output ports without changing the schema."""-- if isinstance(value, dict) and "value" not in value:- return {**value, "value": None}- return value-- sequence: int | None = Field(default=None, ge=0)-- model_config = ConfigDict(extra="allow")---# Compatibility aliases for workers that use shorter protocol names.-ExecutionRef = ExecutionReference-PreparedExecutionRef = ExecutionReference--_EdgeListMutationParams = ParamSpec("_EdgeListMutationParams")_EdgeListMutationResult = TypeVar("_EdgeListMutationResult")diff --git a/invokeai/app/services/shared/graph_models.py b/invokeai/app/services/shared/graph_models.pynew file mode 100644index 0000000000..3aaa7972b9--- /dev/null+++ b/invokeai/app/services/shared/graph_models.py@@ -0,0 +1,160 @@+from typing import Any, Literal, Optional++from pydantic import BaseModel, ConfigDict, model_validator+from pydantic.fields import Field++from invokeai.app.util.misc import uuid_string+++class EdgeConnection(BaseModel):+ model_config = ConfigDict(frozen=True)++ node_id: str = Field(description="The id of the node for this edge connection")+ field: str = Field(description="The field for this connection")++ def __eq__(self, other):+ return (+ isinstance(other, self.__class__)+ and getattr(other, "node_id", None) == self.node_id+ and getattr(other, "field", None) == self.field+ )++ def __hash__(self):+ return hash(f"{self.node_id}.{self.field}")+++class Edge(BaseModel):+ model_config = ConfigDict(frozen=True)++ type: Literal["default", "loop_linkage"] = Field(+ default="default",+ description="The kind of relationship represented by this edge",+ )+ source: EdgeConnection = Field(description="The connection for the edge's from node and field")+ destination: EdgeConnection = Field(description="The connection for the edge's to node and field")++ def __str__(self):+ return f"{self.source.node_id}.{self.source.field} -> {self.destination.node_id}.{self.destination.field}"+++PreparedExecState = Literal["pending", "ready", "executed", "skipped"]+WorkflowCallStatus = Literal["waiting_for_child", "running_child", "completed", "failed"]+++class WorkflowCallFrame(BaseModel):+ """Represents one workflow-call frame in a nested call chain."""++ prepared_call_node_id: str = Field(description="The prepared exec node id for the call site.")+ source_call_node_id: str = Field(description="The source graph node id for the call site.")+ workflow_id: str = Field(description="The saved workflow being called.")+ depth: int = Field(description="The 1-based depth of this call frame.", ge=1)+++class WorkflowCallExecution(BaseModel):+ """Tracks one parent/child workflow-call relationship and its lifecycle."""++ id: str = Field(description="The workflow-call execution id.", default_factory=uuid_string)+ parent_session_id: str = Field(description="The parent graph execution state id.")+ child_session_id: Optional[str] = Field(default=None, description="The child graph execution state id, if any.")+ prepared_call_node_id: str = Field(description="The prepared exec node id for the parent call site.")+ source_call_node_id: str = Field(description="The source graph node id for the parent call site.")+ workflow_id: str = Field(description="The saved workflow being called.")+ depth: int = Field(description="The 1-based depth of this call frame.", ge=1)+ status: WorkflowCallStatus = Field(description="The current workflow-call lifecycle state.")+ error_message: Optional[str] = Field(default=None, description="Failure reason, if the call failed.")+ child_session_ids: list[str] = Field(default_factory=list, description="All child graph execution state ids.")+ child_item_ids: list[int] = Field(default_factory=list, description="Child queue item ids in enqueue order.")+ expected_child_count: int = Field(default=1, ge=1, description="The number of child executions for this call.")+ completed_child_item_ids: list[int] = Field(+ default_factory=list,+ description="The child queue item ids whose workflow_return outputs have been aggregated.",+ )+ aggregated_values: dict[str, list[Any]] = Field(+ default_factory=dict,+ description="The aggregated workflow_return values accumulated from child executions.",+ )+ child_outputs: dict[int, dict[str, Any]] = Field(+ default_factory=dict,+ description="Workflow return values keyed by child queue item id.",+ )+++class WorkflowCallParentRef(BaseModel):+ """Reference from a child execution state back to its parent workflow-call relationship."""++ workflow_call_id: str = Field(description="The workflow-call execution id.")+ parent_session_id: str = Field(description="The parent graph execution state id.")+ prepared_call_node_id: str = Field(description="The prepared exec node id for the parent call site.")+ source_call_node_id: str = Field(description="The source graph node id for the parent call site.")+ workflow_id: str = Field(description="The saved workflow being called.")+ depth: int = Field(description="The 1-based depth of this call frame.", ge=1)+++class ExecutionFrame(BaseModel):+ """Stable execution location for a prepared node."""++ frame_id: str = Field(default="", description="Stable frame identifier")+ state_id: str = Field(default="", description="Owning graph execution state id")+ iteration_path: tuple[int, ...] = Field(default_factory=tuple, description="Loop iteration coordinates")+ workflow_call_depth: int = Field(default=0, ge=0, description="Nested workflow-call depth")++ model_config = ConfigDict(extra="allow")+++class ExecutionReference(BaseModel):+ """Stable, frame-aware reference to one prepared execution node.++ This intentionally stays independent from invocation-context/effect models. The execution engine can reconcile+ this small compatibility type with a richer protocol later without changing persisted graph state.+ """++ reference_id: str = Field(default="", description="Stable reference identifier")+ state_id: str = Field(default="", description="Owning graph execution state id")+ exec_node_id: str = Field(default="", description="Prepared execution node id")+ source_node_id: str = Field(default="", description="Authoring graph node id")+ frame: ExecutionFrame = Field(default_factory=ExecutionFrame, description="Execution frame")+ effect_count: Optional[int] = Field(default=None, ge=0, description="Expected effect count, if declared")++ model_config = ConfigDict(extra="allow")++ @property+ def id(self) -> str:+ return self.reference_id++ @property+ def node_id(self) -> str:+ return self.exec_node_id+++class ExecutionToken(BaseModel):+ """Data token owned by one prepared output port.++ Tokens contain no graph edge or association metadata. In particular, loop-linkage edges never become data+ tokens.+ """++ token_id: str = Field(description="Stable token identifier")+ reference_id: str = Field(description="Owning execution reference id")+ owner_node_id: str = Field(description="Prepared node that produced the token")+ port: str = Field(description="Output port name")+ frame: ExecutionFrame = Field(description="Frame that produced the token")+ value: Any = Field(description="Output port value")+ token_kind: Literal["data", "activation", "stream_end"] = Field(default="data")++ @model_validator(mode="before")+ @classmethod+ def _restore_excluded_null_value(cls, value: Any) -> Any:+ """Allow exclude-none runtime snapshots to hydrate nullable output ports without changing the schema."""++ if isinstance(value, dict) and "value" not in value:+ return {**value, "value": None}+ return value++ sequence: int | None = Field(default=None, ge=0)++ model_config = ConfigDict(extra="allow")+++# Compatibility aliases for workers that use shorter protocol names.+ExecutionRef = ExecutionReference+PreparedExecutionRef = ExecutionReferencediff --git a/tests/app/services/shared/test_graph_models.py b/tests/app/services/shared/test_graph_models.pynew file mode 100644index 0000000000..67980515de--- /dev/null+++ b/tests/app/services/shared/test_graph_models.py@@ -0,0 +1,151 @@+import subprocess+import sys+import textwrap++from pydantic import TypeAdapter, model_validator+from pydantic.json_schema import models_json_schema++from invokeai.app.invocations.math import AddInvocation+from invokeai.app.services.shared import graph as graph_facade+from invokeai.app.services.shared import graph_models+++def test_graph_facade_reexports_graph_models() -> None:+ exported_names = (+ "EdgeConnection",+ "Edge",+ "WorkflowCallFrame",+ "WorkflowCallExecution",+ "WorkflowCallParentRef",+ "ExecutionFrame",+ "ExecutionReference",+ "ExecutionToken",+ "PreparedExecState",+ "WorkflowCallStatus",+ "ExecutionRef",+ "PreparedExecutionRef",+ )++ for name in exported_names:+ assert getattr(graph_facade, name) is getattr(graph_models, name)++ assert graph_facade.model_validator is model_validator+++def test_graph_models_preserve_graph_and_execution_state_serialization() -> None:+ source_graph = graph_facade.Graph()+ source_graph.add_node(AddInvocation(id="source", a=1, b=2))+ source_graph.add_node(AddInvocation(id="destination", a=3, b=4))+ edge = graph_facade.Edge(+ source=graph_facade.EdgeConnection(node_id="source", field="value"),+ destination=graph_facade.EdgeConnection(node_id="destination", field="a"),+ )+ source_graph.add_edge(edge)++ execution_ref = graph_facade.ExecutionReference(+ reference_id="state-id:source",+ state_id="state-id",+ exec_node_id="source",+ source_node_id="source",+ frame=graph_facade.ExecutionFrame(state_id="state-id", frame_id="frame-id"),+ )+ execution_token = graph_facade.ExecutionToken(+ token_id="token-id",+ reference_id=execution_ref.reference_id,+ owner_node_id="source",+ port="value",+ frame=execution_ref.frame,+ value=5,+ )+ state = graph_facade.GraphExecutionState(+ id="state-id",+ graph=source_graph,+ execution_graph=source_graph.model_copy(deep=True),+ execution_refs={execution_ref.reference_id: execution_ref},+ execution_tokens={execution_token.token_id: execution_token},+ )++ graph_json = source_graph.model_dump_json()+ restored_graph = TypeAdapter(graph_facade.Graph).validate_json(graph_json)+ assert restored_graph.model_dump(mode="json", warnings=False) == source_graph.model_dump(+ mode="json", warnings=False+ )++ state_json = state.model_dump_json(exclude_none=True)+ restored_state = graph_facade.GraphExecutionState.model_validate_json(state_json)+ assert restored_state.model_dump(mode="json", warnings=False, exclude_none=True) == state.model_dump(+ mode="json", warnings=False, exclude_none=True+ )++ schema_models = [+ (graph_facade.Graph, "serialization"),+ (graph_facade.GraphExecutionState, "serialization"),+ (graph_facade.Edge, "serialization"),+ (graph_facade.EdgeConnection, "serialization"),+ (graph_facade.WorkflowCallFrame, "serialization"),+ (graph_facade.WorkflowCallExecution, "serialization"),+ (graph_facade.WorkflowCallParentRef, "serialization"),+ (graph_facade.ExecutionFrame, "serialization"),+ (graph_facade.ExecutionReference, "serialization"),+ (graph_facade.ExecutionToken, "serialization"),+ ]+ _, schema = models_json_schema(schema_models)+ definitions = schema["$defs"]+ assert {+ "Graph",+ "GraphExecutionState",+ "Edge",+ "EdgeConnection",+ "WorkflowCallFrame",+ "WorkflowCallExecution",+ "WorkflowCallParentRef",+ "ExecutionFrame",+ "ExecutionReference",+ "ExecutionToken",+ } <= definitions.keys()+ assert {"id", "nodes", "edges"} <= definitions["Graph"]["properties"].keys()+ assert {"id", "graph", "execution_graph", "execution_refs", "execution_tokens"} <= definitions[+ "GraphExecutionState"+ ]["properties"].keys()+ assert {"source", "destination", "type"} <= definitions["Edge"]["properties"].keys()+ assert {"reference_id", "exec_node_id", "frame"} <= definitions["ExecutionReference"]["properties"].keys()+ assert {"token_id", "reference_id", "owner_node_id", "value"} <= definitions["ExecutionToken"]["properties"].keys()+++def test_graph_models_preserve_lazy_networkx_and_registry_behavior() -> None:+ script = """+ import builtins+ import sys++ real_import = builtins.__import__++ def blocked_import(name, globals=None, locals=None, fromlist=(), level=0):+ if name == "networkx" or name.startswith("networkx."):+ raise ModuleNotFoundError("No module named 'networkx'")+ return real_import(name, globals, locals, fromlist, level)++ builtins.__import__ = blocked_import+ from invokeai.app.invocations.baseinvocation import InvocationRegistry++ import invokeai.app.services.shared.graph_models # noqa: F401++ from invokeai.app.services.shared.graph import * # noqa: F401 F403++ registered_classes = set(InvocationRegistry.get_invocation_classes())+ assert any(cls.__name__ == "AddInvocation" and cls.get_type() == "add" for cls in registered_classes)+ assert any(cls.__name__ == "IfInvocation" and cls.get_type() == "if" for cls in registered_classes)++ assert "networkx" not in sys.modules+ print("GRAPH_MODELS_COMPATIBLE")+ """++ result = subprocess.run(+ [sys.executable, "-c", textwrap.dedent(script)],+ capture_output=True,+ text=True,+ timeout=300,+ check=False,+ )++ assert result.returncode == 0, result.stderr+ assert "GRAPH_MODELS_COMPATIBLE" in result.stdout