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 runtime records
JPPhotobd9b2f1eed16
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 36fb799825..6bce607f73 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -98,6 +98,11 @@ from invokeai.app.services.shared.graph_models import (WorkflowCallParentRef, # noqa: F401WorkflowCallStatus, # noqa: F401)+from invokeai.app.services.shared.graph_runtime_records import (+ _ApplyTransaction,+ _PreparedExecNodeMetadata,+ _PreparedExecRegistry,+)from invokeai.app.services.shared.graph_validation import (_RESERVED_EFFECT_PORTS,COLLECTION_FIELD,@@ -159,119 +164,6 @@ class _BodyIterateCollectFanIn:collector_id: str-@dataclass-class _PreparedExecNodeMetadata:- """Cached metadata for a materialized execution node."""-- source_node_id: str- iteration_path: Optional[tuple[int, ...]] = None- state: PreparedExecState = "pending"---class _ApplyTransaction:- """Small undo journal for scheduler mutations made by GraphExecutionState.apply()."""-- def __init__(self) -> None:- self._undo: list[Callable[[], None]] = []- self._recorded: set[tuple[Any, ...]] = set()-- def record_once(self, key: tuple[Any, ...], undo: Callable[[], None]) -> None:- if key in self._recorded:- return- self._recorded.add(key)- self._undo.append(undo)-- def record(self, undo: Callable[[], None]) -> None:- self._undo.append(undo)-- def rollback(self) -> None:- for undo in reversed(self._undo):- undo()---class _PreparedExecRegistry:- """Tracks prepared execution nodes and their relationship to source graph nodes."""-- def __init__(- self,- prepared_source_mapping: dict[str, str],- source_prepared_mapping: dict[str, set[str]],- prepared_iteration_paths: dict[str, tuple[int, ...]],- metadata: dict[str, _PreparedExecNodeMetadata],- on_iteration_path_change: Callable[[str], None] | None = None,- state: Optional["GraphExecutionState"] = None,- ) -> None:- self._prepared_source_mapping = prepared_source_mapping- self._source_prepared_mapping = source_prepared_mapping- self._prepared_iteration_paths = prepared_iteration_paths- self._metadata = metadata- self._on_iteration_path_change = on_iteration_path_change- self._state = state-- def _set_mapping(self, mapping: dict[Any, Any], key: Any, value: Any) -> None:- if self._state is not None:- self._state._tx_set_mapping(mapping, key, value)- else:- mapping[key] = value-- def _pop_mapping(self, mapping: dict[Any, Any], key: Any) -> None:- if self._state is not None:- self._state._tx_pop_mapping(mapping, key)- else:- mapping.pop(key, None)-- def _set_attr(self, obj: Any, name: str, value: Any) -> None:- if self._state is not None:- self._state._tx_set_attr(obj, name, value)- else:- setattr(obj, name, value)-- def register(self, exec_node_id: str, source_node_id: str) -> None:- self._set_mapping(self._prepared_source_mapping, exec_node_id, source_node_id)- self._pop_mapping(self._prepared_iteration_paths, exec_node_id)- self._set_mapping(self._metadata, exec_node_id, _PreparedExecNodeMetadata(source_node_id=source_node_id))- if source_node_id not in self._source_prepared_mapping:- self._set_mapping(self._source_prepared_mapping, source_node_id, set())- if self._state is not None:- self._state._tx_add_set(self._source_prepared_mapping[source_node_id], exec_node_id)- else:- self._source_prepared_mapping[source_node_id].add(exec_node_id)-- def get_metadata(self, exec_node_id: str) -> _PreparedExecNodeMetadata:- metadata = self._metadata.get(exec_node_id)- if metadata is None:- metadata = _PreparedExecNodeMetadata(source_node_id=self._prepared_source_mapping[exec_node_id])- self._set_mapping(self._metadata, exec_node_id, metadata)- return metadata-- def get_source_node_id(self, exec_node_id: str) -> str:- metadata = self._metadata.get(exec_node_id)- if metadata is not None:- return metadata.source_node_id- return self._prepared_source_mapping[exec_node_id]-- def get_prepared_ids(self, source_node_id: str) -> set[str]:- return self._source_prepared_mapping.get(source_node_id, set())-- def set_state(self, exec_node_id: str, state: PreparedExecState) -> None:- self._set_attr(self.get_metadata(exec_node_id), "state", state)-- def get_iteration_path(self, exec_node_id: str) -> Optional[tuple[int, ...]]:- metadata = self._metadata.get(exec_node_id)- if metadata is not None and metadata.iteration_path is not None:- return metadata.iteration_path- iteration_path = self._prepared_iteration_paths.get(exec_node_id)- if iteration_path is not None:- self._set_attr(self.get_metadata(exec_node_id), "iteration_path", iteration_path)- return iteration_path-- def set_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> None:- self._set_mapping(self._prepared_iteration_paths, exec_node_id, iteration_path)- self._set_attr(self.get_metadata(exec_node_id), "iteration_path", iteration_path)- if self._on_iteration_path_change is not None:- self._on_iteration_path_change(exec_node_id)--class _IfActivationController:"""Own activation admission for concrete execution nodes.diff --git a/invokeai/app/services/shared/graph_runtime_records.py b/invokeai/app/services/shared/graph_runtime_records.pynew file mode 100644index 0000000000..e7bd075d5f--- /dev/null+++ b/invokeai/app/services/shared/graph_runtime_records.py@@ -0,0 +1,127 @@+import sys+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Callable, Optional++from invokeai.app.services.shared.graph_models import PreparedExecState++if TYPE_CHECKING:+ from invokeai.app.services.shared.graph import GraphExecutionState+++class _ApplyTransaction:+ """Small undo journal for scheduler mutations made by GraphExecutionState.apply()."""++ def __init__(self) -> None:+ self._undo: list[Callable[[], None]] = []+ self._recorded: set[tuple[Any, ...]] = set()++ def record_once(self, key: tuple[Any, ...], undo: Callable[[], None]) -> None:+ if key in self._recorded:+ return+ self._recorded.add(key)+ self._undo.append(undo)++ def record(self, undo: Callable[[], None]) -> None:+ self._undo.append(undo)++ def rollback(self) -> None:+ for undo in reversed(self._undo):+ undo()+++@dataclass+class _PreparedExecNodeMetadata:+ """Cached metadata for a materialized execution node."""++ source_node_id: str+ iteration_path: Optional[tuple[int, ...]] = None+ state: PreparedExecState = "pending"+++def _new_prepared_exec_node_metadata(source_node_id: str) -> _PreparedExecNodeMetadata:+ graph_facade = sys.modules.get("invokeai.app.services.shared.graph")+ metadata_type = getattr(graph_facade, "_PreparedExecNodeMetadata", _PreparedExecNodeMetadata)+ return metadata_type(source_node_id=source_node_id)+++class _PreparedExecRegistry:+ """Tracks prepared execution nodes and their relationship to source graph nodes."""++ def __init__(+ self,+ prepared_source_mapping: dict[str, str],+ source_prepared_mapping: dict[str, set[str]],+ prepared_iteration_paths: dict[str, tuple[int, ...]],+ metadata: dict[str, _PreparedExecNodeMetadata],+ on_iteration_path_change: Callable[[str], None] | None = None,+ state: Optional["GraphExecutionState"] = None,+ ) -> None:+ self._prepared_source_mapping = prepared_source_mapping+ self._source_prepared_mapping = source_prepared_mapping+ self._prepared_iteration_paths = prepared_iteration_paths+ self._metadata = metadata+ self._on_iteration_path_change = on_iteration_path_change+ self._state = state++ def _set_mapping(self, mapping: dict[Any, Any], key: Any, value: Any) -> None:+ if self._state is not None:+ self._state._tx_set_mapping(mapping, key, value)+ else:+ mapping[key] = value++ def _pop_mapping(self, mapping: dict[Any, Any], key: Any) -> None:+ if self._state is not None:+ self._state._tx_pop_mapping(mapping, key)+ else:+ mapping.pop(key, None)++ def _set_attr(self, obj: Any, name: str, value: Any) -> None:+ if self._state is not None:+ self._state._tx_set_attr(obj, name, value)+ else:+ setattr(obj, name, value)++ def register(self, exec_node_id: str, source_node_id: str) -> None:+ self._set_mapping(self._prepared_source_mapping, exec_node_id, source_node_id)+ self._pop_mapping(self._prepared_iteration_paths, exec_node_id)+ self._set_mapping(self._metadata, exec_node_id, _new_prepared_exec_node_metadata(source_node_id))+ if source_node_id not in self._source_prepared_mapping:+ self._set_mapping(self._source_prepared_mapping, source_node_id, set())+ if self._state is not None:+ self._state._tx_add_set(self._source_prepared_mapping[source_node_id], exec_node_id)+ else:+ self._source_prepared_mapping[source_node_id].add(exec_node_id)++ def get_metadata(self, exec_node_id: str) -> _PreparedExecNodeMetadata:+ metadata = self._metadata.get(exec_node_id)+ if metadata is None:+ metadata = _new_prepared_exec_node_metadata(self._prepared_source_mapping[exec_node_id])+ self._set_mapping(self._metadata, exec_node_id, metadata)+ return metadata++ def get_source_node_id(self, exec_node_id: str) -> str:+ metadata = self._metadata.get(exec_node_id)+ if metadata is not None:+ return metadata.source_node_id+ return self._prepared_source_mapping[exec_node_id]++ def get_prepared_ids(self, source_node_id: str) -> set[str]:+ return self._source_prepared_mapping.get(source_node_id, set())++ def set_state(self, exec_node_id: str, state: PreparedExecState) -> None:+ self._set_attr(self.get_metadata(exec_node_id), "state", state)++ def get_iteration_path(self, exec_node_id: str) -> Optional[tuple[int, ...]]:+ metadata = self._metadata.get(exec_node_id)+ if metadata is not None and metadata.iteration_path is not None:+ return metadata.iteration_path+ iteration_path = self._prepared_iteration_paths.get(exec_node_id)+ if iteration_path is not None:+ self._set_attr(self.get_metadata(exec_node_id), "iteration_path", iteration_path)+ return iteration_path++ def set_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> None:+ self._set_mapping(self._prepared_iteration_paths, exec_node_id, iteration_path)+ self._set_attr(self.get_metadata(exec_node_id), "iteration_path", iteration_path)+ if self._on_iteration_path_change is not None:+ self._on_iteration_path_change(exec_node_id)diff --git a/tests/app/services/shared/test_graph_runtime_records.py b/tests/app/services/shared/test_graph_runtime_records.pynew file mode 100644index 0000000000..82d7bd45e2--- /dev/null+++ b/tests/app/services/shared/test_graph_runtime_records.py@@ -0,0 +1,92 @@+import subprocess+import sys+import textwrap++from invokeai.app.services.shared import graph as graph_facade+from invokeai.app.services.shared import graph_runtime_records+++def test_runtime_records_import_without_graph_cycle() -> None:+ script = textwrap.dedent(+ """+ import sys++ from invokeai.app.services.shared import graph_runtime_records++ assert graph_runtime_records._PreparedExecRegistry+ assert "invokeai.app.services.shared.graph" not in sys.modules+ """+ )+ result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=False)+ assert result.returncode == 0, result.stderr+++def test_graph_facade_reexports_runtime_record_aliases() -> None:+ assert graph_facade._ApplyTransaction is graph_runtime_records._ApplyTransaction+ assert graph_facade._PreparedExecNodeMetadata is graph_runtime_records._PreparedExecNodeMetadata+ assert graph_facade._PreparedExecRegistry is graph_runtime_records._PreparedExecRegistry+++def test_graph_facade_metadata_alias_controls_registry_metadata(monkeypatch) -> None:+ class PatchedMetadata(graph_facade._PreparedExecNodeMetadata):+ pass++ monkeypatch.setattr(graph_facade, "_PreparedExecNodeMetadata", PatchedMetadata)+ prepared_source_mapping = {}+ source_prepared_mapping = {}+ registry = graph_runtime_records._PreparedExecRegistry(+ prepared_source_mapping,+ source_prepared_mapping,+ {},+ {},+ )++ registry.register("registered-exec-node", "source-node")+ assert type(registry.get_metadata("registered-exec-node")) is PatchedMetadata++ prepared_source_mapping["lazy-exec-node"] = "source-node"+ assert type(registry.get_metadata("lazy-exec-node")) is PatchedMetadata+++def test_standalone_registry_lifecycle_and_lazy_metadata() -> None:+ prepared_source_mapping = {"exec-node": "source-node"}+ source_prepared_mapping = {"source-node": {"exec-node"}}+ prepared_iteration_paths = {"exec-node": (2, 3)}+ metadata = {}+ changed: list[str] = []+ registry = graph_runtime_records._PreparedExecRegistry(+ prepared_source_mapping,+ source_prepared_mapping,+ prepared_iteration_paths,+ metadata,+ on_iteration_path_change=changed.append,+ )++ assert registry.get_source_node_id("exec-node") == "source-node"+ assert "exec-node" not in metadata+ assert registry.get_iteration_path("exec-node") == (2, 3)+ assert metadata["exec-node"].iteration_path == (2, 3)++ registry.set_state("exec-node", "ready")+ registry.set_iteration_path("exec-node", (4,))+ assert metadata["exec-node"].state == "ready"+ assert prepared_iteration_paths["exec-node"] == (4,)+ assert changed == ["exec-node"]++ registry.register("new-exec-node", "source-node")+ assert registry.get_prepared_ids("source-node") == {"exec-node", "new-exec-node"}+ assert registry.get_metadata("new-exec-node").source_node_id == "source-node"+ assert "new-exec-node" not in prepared_iteration_paths+++def test_apply_transaction_record_once_rolls_back_in_reverse_order() -> None:+ transaction = graph_runtime_records._ApplyTransaction()+ undone: list[str] = []++ transaction.record_once(("first",), lambda: undone.append("first"))+ transaction.record_once(("first",), lambda: undone.append("duplicate"))+ transaction.record(lambda: undone.append("second"))++ transaction.rollback()++ assert undone == ["second", "first"]