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
fix(intermediates): protect cached media during active sessions
Josh Corbette73f875899ea
diff --git a/docs/src/content/docs/features/intermediates.mdx b/docs/src/content/docs/features/intermediates.mdxindex 1f7a687f76..ca53d60ec5 100644--- a/docs/src/content/docs/features/intermediates.mdx+++ b/docs/src/content/docs/features/intermediates.mdx@@ -17,7 +17,7 @@ Administrators start on their own account. **Show everyone** expands the view toA normal clear deletes only safe items. It always keeps:-- anything a pending, waiting or running job produced or uses as an input;+- anything a pending, waiting or running job produced or uses as an input, including cached images and videos reused from an earlier job;- anything created in the last 30 minutes, so an upload the browser is about to reference or enqueue is never collected;- anything the open webv2 editor has used, including unsaved edits and canvas undo history; the browser refreshes this temporary hold while it is open;- anything a saved project or library workflow still names, such as canvas staging candidates or cropped reference images;diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.pyindex 351e22a88d..7469d06553 100644--- a/invokeai/app/invocations/baseinvocation.py+++ b/invokeai/app/invocations/baseinvocation.py@@ -42,6 +42,7 @@ from invokeai.app.invocations.fields import ()from invokeai.app.services.config.config_default import get_configfrom invokeai.app.services.shared.invocation_context import InvocationContext+from invokeai.app.services.shared.media_references import extract_media_referencesfrom invokeai.app.util.metaenum import MetaEnumfrom invokeai.app.util.misc import uuid_stringfrom invokeai.backend.util.logging import InvokeAILogger@@ -243,6 +244,11 @@ class BaseInvocation(ABC, BaseModel):if self.use_cache:key = services.invocation_cache.create_key(self)cached_value = services.invocation_cache.get(key)+ if cached_value is not None and services.intermediates is not None:+ references = extract_media_references(cached_value.model_dump(mode="json"))+ if not services.intermediates.hold_cached_media(context._data.queue_item.session_id, references):+ services.invocation_cache.delete(key)+ cached_value = Noneif cached_value is None:services.logger.debug(f'Invocation cache miss for type "{self.get_type()}": {self.id}')output = self.invoke(context)diff --git a/invokeai/app/services/intermediates/intermediates_base.py b/invokeai/app/services/intermediates/intermediates_base.pyindex 6cf368bc95..f09a50ed1f 100644--- a/invokeai/app/services/intermediates/intermediates_base.py+++ b/invokeai/app/services/intermediates/intermediates_base.py@@ -11,6 +11,7 @@ from invokeai.app.services.intermediates.intermediates_common import (IntermediatesSummary,IntermediatesSummarySort,)+from invokeai.app.services.shared.media_references import MediaReferences@dataclass(frozen=True)@@ -24,6 +25,11 @@ class IntermediatesCaller:class IntermediatesServiceBase(ABC):"""Scoped cleanup of intermediate images and videos under one eligibility policy."""+ @abstractmethod+ def hold_cached_media(self, session_id: str, references: MediaReferences) -> bool:+ """Pin existing cached media until the consuming queue session ends; False means recompute."""+ pass+@abstractmethoddef replace_browser_hold(self, caller: IntermediatesCaller, lease_id: str, request: IntermediatesBrowserHoldRequestdiff --git a/invokeai/app/services/intermediates/intermediates_default.py b/invokeai/app/services/intermediates/intermediates_default.pyindex 5438cf7d8c..158d5703a1 100644--- a/invokeai/app/services/intermediates/intermediates_default.py+++ b/invokeai/app/services/intermediates/intermediates_default.py@@ -55,6 +55,7 @@ from invokeai.app.services.intermediates.intermediates_records_sqlite import ()from invokeai.app.services.invoker import Invokerfrom invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResult+from invokeai.app.services.shared.media_references import MediaReferencesDELETE_BATCH_SIZE = 200MEASURE_BATCH_SIZE = 200@@ -180,6 +181,9 @@ class IntermediatesService(IntermediatesServiceBase):# region summary+ def hold_cached_media(self, session_id: str, references: MediaReferences) -> bool:+ return self._records.hold_cached_media(session_id, references)+def replace_browser_hold(self, caller: IntermediatesCaller, lease_id: str, request: IntermediatesBrowserHoldRequest) -> None:diff --git a/invokeai/app/services/intermediates/intermediates_records_sqlite.py b/invokeai/app/services/intermediates/intermediates_records_sqlite.pyindex 599972ff5a..ad18745a19 100644--- a/invokeai/app/services/intermediates/intermediates_records_sqlite.py+++ b/invokeai/app/services/intermediates/intermediates_records_sqlite.py@@ -26,6 +26,7 @@ from invokeai.app.services.intermediates.intermediates_common import (IntermediatesKindCounts,IntermediatesScopeTarget,)+from invokeai.app.services.shared.media_references import MediaReferencesfrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabaseMediaKind = Literal["image", "video"]@@ -85,6 +86,49 @@ class IntermediatesRecordsSqlite:# why it is rebuilt on every call rather than skipped on an unchanged set.self._active_inputs: dict[int, tuple[str, set[str], set[str]]] = {}+ @staticmethod+ def _prepare_session_holds(cursor: sqlite3.Cursor) -> None:+ # These holds share the cache's process lifetime. After restart the cache is empty and+ # recovered queue sessions protect their serialized inputs through the normal scan.+ cursor.execute(+ "CREATE TEMP TABLE IF NOT EXISTS intermediates_session_media "+ "(session_id TEXT, kind TEXT, name TEXT, PRIMARY KEY(session_id, kind, name)) WITHOUT ROWID;"+ )+ statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)+ cursor.execute(+ "DELETE FROM temp.intermediates_session_media WHERE session_id NOT IN "+ f"(SELECT session_id FROM session_queue WHERE status IN ({statuses}));"+ )++ def hold_cached_media(self, session_id: str, references: MediaReferences) -> bool:+ if references.is_empty():+ return True+ with self._db.transaction() as cursor:+ self._prepare_session_holds(cursor)+ statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)+ cursor.execute(+ f"SELECT 1 FROM session_queue WHERE session_id = ? AND status IN ({statuses});", (session_id,)+ )+ if cursor.fetchone() is None:+ return False+ held: list[tuple[str, str, str]] = []+ for kind, names in (("image", references.images), ("video", references.videos)):+ table, name_column, _ = _TABLES[cast(MediaKind, kind)]+ ordered = sorted(names)+ for start in range(0, len(ordered), _MAX_SQL_VARIABLES):+ chunk = ordered[start : start + _MAX_SQL_VARIABLES]+ placeholders = ",".join("?" for _ in chunk)+ cursor.execute(f"SELECT COUNT(*) FROM {table} WHERE {name_column} IN ({placeholders});", chunk)+ if cursor.fetchone()[0] != len(chunk):+ # Deletion won the race after the cache lookup. Do not return a stale+ # output; invoking the node again will create fresh media instead.+ return False+ held.extend((session_id, kind, name) for name in ordered)+ # The existence check and hold commit share the deleting transaction's lock. Cleanup+ # either deletes first (a cache miss), or observes this active session's hold.+ cursor.executemany("INSERT OR IGNORE INTO temp.intermediates_session_media VALUES (?, ?, ?);", held)+ return True+def replace_browser_hold(self, user_id: str, lease_id: str, images: Sequence[str], videos: Sequence[str]) -> None:with self._db.transaction() as cursor:cursor.execute(@@ -239,6 +283,7 @@ class IntermediatesRecordsSqlite:Runs on the caller's transaction so a classification and the enqueue it might race areordered by the database lock, never by a stale cache."""+ self._prepare_session_holds(cursor)cursor.execute("""--sqlCREATE TEMP TABLE IF NOT EXISTS intermediates_active_media (@@ -293,6 +338,10 @@ class IntermediatesRecordsSqlite:cursor.executemany("INSERT OR IGNORE INTO temp.intermediates_active_media (kind, name) VALUES (?, ?);", sorted(rows))+ cursor.execute(+ "INSERT OR IGNORE INTO temp.intermediates_active_media (kind, name) "+ "SELECT kind, name FROM temp.intermediates_session_media;"+ )# endregiondiff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 317a4e16b0..854caf387c 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -289,6 +289,13 @@ This behavior is implemented in the runtime scheduler, not in the invocation bod1. Finish when `next()` returns `None` and the execution state is not paused waiting on a workflow call boundary.+When an invocation reuses cached media, `BaseInvocation.invoke_internal()` registers a temporary hold for the consuming+queue session before returning the cached output. The intermediates service checks that every referenced image/video+record still exists and registers the hold under the same database lock as cleanup. If cleanup already deleted a+record, the invocation recomputes its output. Holds remain effective while the session is pending, running or waiting;+terminal/deleted sessions are pruned on the next cache hold or cleanup query. Holds share the cache's process lifetime;+after restart, persisted queue sessions supply their own media references and the invocation cache is empty.+In normal execution, all runtime expansion occurs in `execution_graph` with traceability back to source nodes.## 6) Invariantsdiff --git a/tests/app/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.pyindex e18925913f..bab69bd29c 100644--- a/tests/app/services/intermediates/test_intermediates_service.py+++ b/tests/app/services/intermediates/test_intermediates_service.py@@ -1139,3 +1139,138 @@ def test_large_single_row_clears_in_bounded_batches_past_protected_items(assert second.impact.delete_images == 1assert second_result.progress.deleted_images == 1assert _exists(invoker, "protected-first.png")++[email protected]("cleanup_wins_race", [False, True])+def test_running_graph_keeps_cached_media_or_recomputes_if_cleanup_won(+ invoker, service, monkeypatch, cleanup_wins_race+):+ from threading import Event++ from invokeai.app.invocations.image import BlankImageInvocation, ImageCropInvocation+ from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache+ from invokeai.app.services.names.names_default import SimpleNameService+ from invokeai.app.services.progress_previews.progress_previews_default import MemoryProgressPreviews+ from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner+ from invokeai.app.services.shared.graph import Graph, GraphExecutionState+ from invokeai.app.services.urls.urls_default import LocalUrlService+ from tests.app.services.workflow_call_test_utils import _DummyStats+ from tests.test_nodes import create_edge++ services = invoker.services+ services.session_queue.start(invoker)+ services.configuration.node_cache_size = 512+ services.names = SimpleNameService()+ services.urls = LocalUrlService()+ services.performance_statistics = _DummyStats()+ services.progress_previews = MemoryProgressPreviews()+ services.tensors = MagicMock()+ services.conditioning = MagicMock()+ cache = services.invocation_cache = MemoryInvocationCache(max_cache_size=512)+ cache.start(invoker)+ runner = DefaultSessionRunner()+ runner.start(services, Event())+ graph = Graph()+ graph.add_node(BlankImageInvocation(id="blank", width=8, height=8, is_intermediate=True))+ graph.add_node(ImageCropInvocation(id="crop", x=0, y=0, width=4, height=4, use_cache=False))+ graph.add_edge(create_edge("blank", "image", "crop", "image"))++ def queued_session():+ session = GraphExecutionState(graph=graph.model_copy(deep=True))+ item_id = _enqueue_row(+ invoker, session_id=session.id, status="in_progress", session_json=session.model_dump_json()+ )+ return services.session_queue.get_queue_item(item_id)++ first = queued_session()+ first_blank = first.session.next()+ runner.run_node(first_blank, first)+ assert not first.session.has_error()+ image_name = first.session.results[first_blank.id].image.image_name+ runner.run_node(first.session.next(), first)+ assert first.session.is_complete() and not first.session.has_error()+ services.session_queue.save_queue_item_session(first.item_id, first.session)+ with services.image_records._db.transaction() as cursor:+ cursor.execute("UPDATE session_queue SET status = 'completed' WHERE item_id = ?", (first.item_id,))+ cursor.execute("UPDATE images SET created_at = '2020-01-01 00:00:00.000' WHERE image_name = ?", (image_name,))++ if cleanup_wins_race:+ real_get = cache.get++ def get_then_cleanup(key):+ output = real_get(key)+ if output is not None:+ _, completed = _run(service, ALICE, _owner("alice"))+ assert completed.progress.deleted_images == 1+ return output++ monkeypatch.setattr(cache, "get", get_then_cleanup)++ second = queued_session()+ second_blank = second.session.next()+ runner.run_node(second_blank, second)+ assert not second.session.has_error()+ assert cache.get_status().hits == 1+ second_image = second.session.results[second_blank.id].image.image_name+ if cleanup_wins_race:+ assert second_image != image_name+ else:+ assert second_image == image_name+ record = services.image_records.get(image_name)+ assert record.session_id == first.session_id+ stored_second = services.session_queue.get_queue_item(second.item_id)+ assert image_name not in stored_second.session.model_dump_json()+ for mode in ("safe", "force"):+ preview, completed = _run(service, ALICE, _owner("alice"), mode=mode)+ assert preview.impact.keep_active_images == 1+ assert completed.progress.deleted_images == 0+ assert services.image_files.get_path(image_name, image_subfolder=record.image_subfolder).exists()++ runner.run_node(second.session.next(), second)+ assert second.session.is_complete() and not second.session.has_error()+ services.session_queue.save_queue_item_session(second.item_id, second.session)+ with services.image_records._db.transaction() as cursor:+ cursor.execute("UPDATE session_queue SET status = 'completed' WHERE item_id = ?", (second.item_id,))+ if not cleanup_wins_race:+ _, completed = _run(service, ALICE, _owner("alice"))+ assert completed.progress.deleted_images == 1++[email protected]("mode", ["safe", "force"])+def test_cached_media_holds_guard_frozen_targets_until_all_consuming_sessions_end(invoker, service, mode):+ from invokeai.app.services.shared.media_references import MediaReferences++ _seed_image(invoker, "cached.png")+ _seed_video(invoker, "cached.mp4")+ preview = service.create_preview(IntermediatesPreviewRequest(mode=mode, scope=_owner("alice")), ALICE)+ first = _enqueue_row(invoker, session_id="first-consumer", status="in_progress")+ second = _enqueue_row(invoker, session_id="second-consumer", status="waiting")+ references = MediaReferences(images={"cached.png"}, videos={"cached.mp4"})+ assert service.hold_cached_media("first-consumer", references)+ assert service.hold_cached_media("second-consumer", references)+ started = service.start_operation(+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="before-cache-hit"), ALICE+ )+ protected = _wait(service, started.operation_id)+ assert protected.progress.retained_images == protected.progress.retained_videos == 1++ with invoker.services.image_records._db.transaction() as cursor:+ cursor.execute("UPDATE session_queue SET status = 'completed' WHERE item_id = ?", (first,))+ preview, _ = _run(service, ALICE, _owner("alice"), mode=mode)+ assert preview.impact.keep_active_images == preview.impact.keep_active_videos == 1+ with invoker.services.image_records._db.transaction() as cursor:+ cursor.execute("UPDATE session_queue SET status = 'canceled' WHERE item_id = ?", (second,))+ _, completed = _run(service, ALICE, _owner("alice"), mode=mode)+ assert completed.progress.deleted_images == completed.progress.deleted_videos == 1+++def test_missing_cached_media_does_not_leave_a_partial_hold(invoker, service):+ from invokeai.app.services.shared.media_references import MediaReferences++ _seed_image(invoker, "survivor.png")+ _enqueue_row(invoker, session_id="consumer", status="in_progress")+ assert not service.hold_cached_media(+ "consumer", MediaReferences(images={"survivor.png"}, videos={"already-deleted.mp4"})+ )+ _, completed = _run(service, ALICE, _owner("alice"))+ assert completed.progress.deleted_images == 1